NodeJS 的标准刷新?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12510835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Stdout flush for NodeJS?
提问by TonyTakeshi
Is there any stdout flush for nodejs just like python or other languages?
nodejs 是否有任何标准输出刷新,就像 python 或其他语言一样?
sys.stdout.write('some data')
sys.stdout.flush()
Right now I only saw process.stdout.write()for nodejs.
现在我只看到process.stdout.write()了 nodejs。
采纳答案by jrajav
process.stdoutis a WritableStreamobject, 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 drainevent.
process.stdout是一个WritableStream对象,并且该方法会WritableStream.write()自动刷新流(除非它被明确地塞住了)。但是,如果刷新成功,它将返回 true,如果内核缓冲区已满并且还不能写入,它将返回 false。如果需要连续写入多次,则应处理该drain事件。
See the documentation for write.
请参阅的文档write。
回答by jviotti
In newer NodeJS versions, you can pass a callback to .write(), which will be called once the data is flushed:
在较新的 NodeJS 版本中,您可以将回调传递给.write(),该回调将在数据刷新后调用:
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 drainevent:
这与检查.write()结果和注册drain事件完全相同:
var write = sys.stdout.write('some data');
if (!write) {
sys.stdout.once('drain', () => {
console.log('The data has been flushed');
});
}
回答by Jeeva Kumar
There is another function stdoutwhich to clear last output to the terminal which is kind of work like flush
还有另一个功能stdout可以清除终端的最后输出,这有点像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);
cursorTowill move the cursor to position 0which is the starting point
cursorTo将光标移动到0作为起点的位置
use the flushfunction before stdout.writebecause it will clear the screen, if you put after you will not see any output
使用flush之前的功能,stdout.write因为它会清除屏幕,如果你在之后你将看不到任何输出

