Catching console.log in node.js?

前端 未结 4 775
野趣味
野趣味 2020-12-30 05:28

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 modu

4条回答
  •  轮回少年
    2020-12-30 05:42

    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.

提交回复
热议问题