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 saw process.stdout.write()
for nodejs.
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.
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');
});
}
write returns true
if the data has been flushed. If it returns false
, you can wait for the 'drain' event.
I think there is no flush
, because that would be a blocking operation.
There is another function stdout
which to clear last output to the terminal which is kind of work like 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
will move the cursor to position 0
which is the starting point
use the flush
function before stdout.write
because it will clear the screen, if you put after you will not see any output