Stdout flush for NodeJS?

前端 未结 2 1285
旧时难觅i
旧时难觅i 2021-02-11 16:28

Is there any stdout flush for nodejs just like python or other languages?

sys.stdout.write(\'some data\')

sys.stdout.flush()

Right now I only

相关标签:
2条回答
  • 2021-02-11 16:49

    process.stdout is a WritableStream object, and the method WritableStream.write() automatically flushes the stream (unless it was explicitly corked). However, it will return true if the flush was successful, and false if the kernel buffer was full and it can't write yet. If you need to write several times in succession, you should handle the drain event.

    See the documentation for write.

    0 讨论(0)
  • 2021-02-11 16:56

    In newer NodeJS versions, you can pass a callback to .write(), which will be called once the data is flushed:

    sys.stdout.write('some data', () => {
      console.log('The data has been flushed');
    });
    

    This is exactly the same as checking .write() result and registering to the drain event:

    let write = sys.stdout.write('some data');
    if (!write) {
      sys.stdout.once('drain', () => {
        console.log('The data has been flushed');
      });
    }
    
    0 讨论(0)
提交回复
热议问题