Created
November 3, 2022 08:11
-
-
Save gagan-bansal/0a80b52fb6ca353ede21fdeece942387 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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