简体   繁体   中英

Synchronous logging with Node.js

I am simply to create some synchronous logging with Node.js.

I believe console.log is synchronous, but I am looking to use process.stdout, a writable stream.

This is what I have so far:

var messages = [];
var okToWrite = true;

process.stdout.on('finish', function () {

    okToWrite = true;
    if (messages.length > 0) {
        runnerLog(messages.pop());
    }

});

module.exports = function runnerLog(data) {

    if (okToWrite) {
        okToWrite = false;
        process.stdout.write(data);
        process.stdout.end();
    }
    else {
        messages.push(data);
    }

};

the problem is that the finish event is never fired, and I also tried listening for the drain event, but that didn't seem to be fired either. Calling process.stdout.end() just seemed to cause problems. Should I be calling process.stdout.flush()?

I am not sure if I need synchronous logging, but either way this code will not lock up the event loop as I am using async I/O and not waiting for anything, etc. It's all evented.

From the docs for Node.js process, it looks like calling end() will throw and finish never gets called:

https://nodejs.org/api/process.html#process_process_stdout

so perhaps I should use a different writable stream other than process.stdout and pipe it to process.stdout? No idea.

It appears that process.stdout.write, at least when directed at a terminal/console is already synchronous. There doesn't appear to be a need to add anything. Furthermore it doesn't appear that the process.stdout stream fires the events needed to make my original design for sync logging possible, as outlined in my question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM