Break in console.log? - node.js

I have an irksome problem in my node.js test code. Somewhere, something prints out an error message using console.log (i think). I am somewhat fastidious about clutter in my logs, so I trying to catch whatever it is. I am 100% sure that it's not in my code, it must be in some library we're using.
This brought me to an interesting question: is it possible to set a breakpoint in console.log? I'm working in WebStorm IDE and I'm running on node.js 4.4.3.

You could overwrite console.log with a custom version that breaks into the debugger:
var _log = console.log.bind(console);
// es6
console.log = (...args) => {
_log(...args);
debugger;
}
// es5
console.log = function() {
_log.apply(null, arguments);
debugger;
}
Here's a one-liner if you'd like to copy/paste into a browser console for a drive test (verified in Chrome 51, Safari 9.1, and Firefox 46):
var _log = console.log.bind(console); console.log = function() { _log.apply(null, arguments); debugger; }

you could try something like this.
process.on('uncaughtException', function(err) {
console.log('Threw Exception: ' + err.stack);
});

Related

How to enable console logging for MongoDB errors?

I am developing a NodeJS application. I had a problem saving an object to the database; the code in my controller was:
console.log("Before save: " + transaction);
transaction = await transaction.save();
console.log("After save");
In the terminal running the Node application, I saw:
Before save: {
_id: ...,
created: ...,
...
}
and nothing more, while the browser page looks like it's loading.
I tried wrapping it in a try-catch block:
try {
transaction = await transaction.save();
} catch (err) {
console.log(err);
}
and I get the same output in the terminal. I suppose that since I don't see the error in the console without the try-catch, I don't see it with it either.
One problem was that the MongoDB collection for that object did not exist (and I asked about it here). But I still have another error.
How can I enable MongoDB to show those errors (missing collection, and the error I am still looking for) in the terminal running NodeJS while I'm in development?
I found the problem: I had omitted a next(); in a pre-save hook:
SomeSchema.pre('save', function(next) {
// any logic you require
if (this.condition) {
// ...
}
next(); // <- this is required, else Mongo won't save nor return
});
So I was not getting an error because there was no error, only a break in the flow of calls.

waitforSelector function in casperjs

hello I am new to Casper and node
I am trying to run a code that scrpping data from a site
but WaitForselector function is not working correctly .
my code is
casper.waitForSelector('.searchAutoSuggstn', function() {
this.echo('Search auto suggestion.'); // this line is printing my console
var data = this.evaluate(function() {
var suggestions = [];
this.echo('Search auto suggestion data.'); //But this line is not printing my console
var element = $('.searchAutoSuggstn .suggestionsList_menu').find('.topProdhead_left').prevAll().filter(function() {
this.echo('omnitrack');
return $(this).data("omnitrack") ;
});
is any boddy can tell me whats the main problem ?
You can't call casper methods such as casper.echo() in casper.evaluate() since evaluate executes code in the context of the browser.
You could use console.log in the browser to output to the javascript console which you can then catch with the hook
casper.on("remote.messsage", function(msg){
// Do something
});

Check if a module exists, if so replace console with it, otherwise not. Not working, console gets undefined

I'm using clim and I replace the console object with it. But I only want to replace it if the module exists.
try {
var console = require('clim')();
} catch(err) {}
console.log('checking..');
If the module doesn't exists it makes the console undefined.
Strangely, saving the console object and replacing doesn't work either
var console_backup = console;
try {
var console = require('clim')();
} catch(err) {
if (err) var console = console_backup;
}
console.log('checking..');
Still throws error (console goes undefined) when clim doesn't exist.
http://runnable.com/U8vlFEpIYtkiV2N9/24850946-console-for-node-js
How to make work replacing the console with clim only when it exists?
Your second attempt is close, but you need to explicitly identity that you want to reference the global console when setting console_backup or it will reference the hoisted, local console variable, even though you haven't declared it yet:
var console_backup = global.console;
try {
var console = require('clim')();
} catch(err) {
if (err) var console = console_backup;
}
console.log('checking..');
or simplify it to:
try {
var console = require('clim')();
} catch(err) {
if (err) console = global.console;
}
console.log('checking..');
You can't overwrite the global console like that. The var console is just creating a local variable that shadows the global console, not even global.console = ... will work.
You could overwrite console.log, etc. individually or overwrite process.stdout.write (what console.log uses internally) which would allow you to hook into stdout writing at a lower level. This would also catch anyone else that may use process.stdout.write directly.

No error being thrown for undefined variable in node.js with express

I am running node.js with express. I wrote a node module with methods in it so when you go to
http://bla.com/module_name/method_name
it will run the method.
The method follows the typical style of
exports.method_name(req, res, next);
my main app does something like this:
app.all("*", resSetup, controller, render);
and controller is the thing that will call the method based on the path.
it seems that if there is an undefined variable error in the method, express will just hang there and not throw any error. Nothing will appear in the console log either. I can put a console message right before and after where the error occurs and the before will appear in the log, and after will not.
I can wrap it in a try/catch and get this:
[ReferenceError: blabla is not defined]
but no line numbers or anything.
My guess is that express is somehow preventing the errors from coming up. When I put the error in the function called "controller" that is directly in the route, it shows that error correctly.
It might not matter too much, but here is the code I am working on:
https://github.com/RobKohr/quick-site/blob/master/index.js
Line 189 is where the method call happens.
Building on Ruairi's comment above, I had this same issue with when using 'q' (https://github.com/kriskowal/q) and promises with express - node would hang and no error was generated.
By adding a catch to the end of the promise 'callback' chain I was able to see the error and print it to console etc.
The code ends up looking like:
export function index(req, res) {
//Create the 'promise'
var request = req.body;
var queryJobID = req.query.jobId;
console.log('queryJobID: ' + queryJobID);
var jobStatusPromsie = jobManager.job.getStatus(queryJobID);
Q.all([jobStatusPromsie])
.then(
function (result) {
var responseData = {};
console.log('Job Status Response received');
if (result != null) {
//Without the .catch below an error here will be 'silent'
console.log('jobStatus result: ' + util.inspect(result, false, null));
responseData['status'] = 'OK';
responseData['progress'] = result.progress;
res.json(responseData);
} else {
console.log('jobStatus Error');
responseData['status'] = 'Error';
}
res.json(responseData);
console.log('jobStatus Response data sent');
},
function (error) {
console.log('Error while getting job status:', error);
res.json("Error");
})
.catch(function(err) {
//handle errors
console.log('Promise error while getting job status:', err);
});
}
Express heavily relies on Nodes asynchronous nature. Seeing errors thrown like on line 30 would give me the creeps if I was maintaining this. Try refactoring your code to only use the next(err) pattern.
The reason that you app is hanging is that Express hasn't finished the HTTP response (eg: res.send()). This means you have broken plumbing where an Error has bubbled up the call stack but not redirected into the Express middleware pipeline. Try registering some error middleware to see if it gets called with your error.

nodeunit fail to exit from my asynchronous tests

Whenever I run my nodeunit test in IDE or console, it run well but fail to exit. Help me please with it!
var store = require('../lib/db');
var list = require('../source/models/mock_deals');
var logger = require('../lib/logging').logger;
exports.setUp = function(done){
logger.info('start test...');
done();
};
exports.tearDown = function(done){
logger.info('end test...');
done();
};
exports.testInsertDeal = function(test){
var length = list.length;
test.equals(length, 2);
store.mongodb.open(function(err,db){
if(err){
logger.error(err);
return;
}
logger.info("mongodb is connected!");
db.collection('deals',function(err,collection){
for(var i=0; i<length; i++){
var item = list[i];
collection.insert(item, function(err, result){
if(err){
logger.error('Fail to insert document deal [' + item.id + ']');
return;
}
logger.info( 'index ' + i + ' : ' +JSON.stringify(item) );
});
}
});
test.expect(1);
});
test.done();
};
I changed to use mongoose instead of mongodb. test still could not exit automatically.
But when I disconnected mongoose in test.tearDown method in my nodeunit test. the test existed correctly.
Add below in you test:
exports.tearDown = function(done){
mongoose.disconnect(function(err){
if(err) {
logger.error(err);
return;
}
logger.info('mongoose is disconnected');
});
done();
};
And more, If I use log4js for logging in my test and configure log4js with reloadSecs: 500 , test will not exist either. After I set reloadSecs to 0, then test exists well. So we need to configure logging.json with option reloadSecs: 0
To summarize: we need to make sure there are no working parts there after all test methods are done. then test will exist correctly.
If you know when your program should exit, you can simply use the following line of code to exit:
process.exit(0);
where 0 is the return code of the program.
Now that isn't really fixing the problem. There is probably a call back still waiting or a connection that is still active keeping your program up and running that isn't shown in the code you posted here. If you don't care to find it, just use process.exit. If you really care to find it, you will have to dig some more. I've never used nodeunit but I have used other node libraries that leave stuff up in their inner workings that keep the program from exiting. In those cases, I usually don't feel like wading through other peoples source code to find out what is going on so I just do the afore mentioned process.exit call.
This should at least give you an option.

Resources