Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching console.log in node.js?

Is there a way that I can catch eventual console output caused by console.log(...) within node.js to prevent cloggering the terminal whilst unit testing a module?

Thanks

like image 209
Industrial Avatar asked Mar 07 '12 21:03

Industrial


People also ask

How do I view console log?

Steps to Open the Console Log in Google Chrome By default, the Inspect will open the "Elements" tab in the Developer Tools. Click on the "Console" tab which is to the right of "Elements". Now you can see the Console and any output that has been written to the Console log.

How do I open the console in node js?

To launch the REPL (Node shell), open command prompt (in Windows) or terminal (in Mac or UNIX/Linux) and type node as shown below. It will change the prompt to > in Windows and MAC. You can now test pretty much any Node.


2 Answers

A better way could be to directly hook up the output you to need to catch data of, because with Linus method if some module write directly to stdout with process.stdout.write('foo') for example, it wont be caught.

var logs = [],

hook_stream = function(_stream, fn) {
    // Reference default write method
    var old_write = _stream.write;
    // _stream now write with our shiny function
    _stream.write = fn;

    return function() {
        // reset to the default write method
        _stream.write = old_write;
    };
},

// hook up standard output
unhook_stdout = hook_stream(process.stdout, function(string, encoding, fd) {
    logs.push(string);
});

// goes to our custom write method
console.log('foo');
console.log('bar');

unhook_stdout();

console.log('Not hooked anymore.');

// Now do what you want with logs stored by the hook
logs.forEach(function(_log) {
    console.log('logged: ' + _log);
});

EDIT

console.log() ends its output with a newline, you may want to strip it so you'd better write:

_stream.write = function(string, encoding, fd) {
    var new_str = string.replace(/\n$/, '');
    fn(new_str, encoding, fd);
};

EDIT

Improved, generic way to do this on any method of any object with async support See the gist.

like image 64
kevin Avatar answered Sep 28 '22 04:09

kevin


module.js:

module.exports = function() {
    console.log("foo");
}

program:

console.log = function() {};
mod = require("./module");
mod();
// Look ma no output!

Edit: Obviously you can collect the log messages for later if you wish:

var log = [];
console.log = function() {
    log.push([].slice.call(arguments));
};
like image 41
Linus Thiel Avatar answered Sep 28 '22 04:09

Linus Thiel