Stdout刷新NodeJS?

是否有像Python或其他语言的任何stdout刷新nodejs?

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

现在我只看到nodejs的process.stdout.write()

process.stdout是一个WritableStream对象,并且方法WritableStream.write()自动刷新stream(除非明确地被塞住)。 但是,如果刷新成功则返回true,如果内核缓冲区已满并且不能写入,则返回false。 如果你需要连续写几次,你应该处理drain事件。

请参阅文档以进行write

在较新的NodeJS版本中,可以将callback传递给.write() ,一旦数据被刷新,将会调用该callback。

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

这与检查.write()结果并注册到drain事件完全相同:

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

如果数据已经被刷新, write返回true 。 如果返回false ,则可以等待“漏”事件。

我认为没有flush ,因为这将是一个阻塞操作。

还有另一个函数stdout清除最后输出到terminal,这是一种工作,如flush

 function flush() { process.stdout.clearLine(); process.stdout.cursorTo(0); } var total = 5000; var current = 0; var percent = 0; var waitingTime = 500; setInterval(function() { current += waitingTime; percent = Math.floor((current / total) * 100); flush(); process.stdout.write(`downloading ... ${percent}%`); if (current >= total) { console.log("\nDone."); clearInterval(this); } }, waitingTime); 

cursorTo将光标移动到位置0 (起点)

stdout.write之前使用flushfunction,因为它会清除屏幕,如果你看不到任何输出