Skip to content

Instantly share code, notes, and snippets.

@gagan-bansal
Created November 3, 2022 08:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gagan-bansal/0a80b52fb6ca353ede21fdeece942387 to your computer and use it in GitHub Desktop.
Save gagan-bansal/0a80b52fb6ca353ede21fdeece942387 to your computer and use it in GitHub Desktop.
const fs = require('fs');
const {LoremIpsum} = require("lorem-ipsum");
const lorem = new LoremIpsum();
const ws = fs.createWriteStream('somefile.txt');
// https://nodejs.org/api/stream.html#stream_event_drain
// Write the data to the supplied writable stream one million times.
// Be attentive to back-pressure.
function writeOneMillionTimes(writer, data, encoding, callback) {
let i = 1000000;
write();
function write() {
let ok = true;
do {
i--;
if (i === 0) {
// Last time!
writer.write(data, encoding, callback);
} else {
// See if we should continue, or wait.
// Don't pass the callback, because we're not done yet.
//ok = writer.write(lorem.generateWords(4) + '\n', encoding);
ok = writer.write(i + data, encoding);
}
} while (i > 0 && ok);
if (i > 0) {
// Had to stop early!
// Write some more once it drains.
writer.once('drain', write);
}
}
}
writeOneMillionTimes(ws, 'test\n', 'utf8', () => {
console.log('all done!');
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment