Last active
October 31, 2022 14:57
-
-
Save stevenkaspar/509f792cbf1194f9fb05e7d60a1fbc73 to your computer and use it in GitHub Desktop.
Nodejs - stream with 'drain' and async/await
This file contains hidden or 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
// prevents "backpressuring" when writing to stream | |
const write = (writer, data) => { | |
return new Promise((resolve) => { | |
if (!writer.write(data)) { | |
writer.once('drain', resolve) | |
} | |
else { | |
resolve() | |
} | |
}) | |
} | |
// usage | |
const run = async () => { | |
const write_stream = fs.createWriteStream('...') | |
const max = 1000000 | |
let current = 0 | |
while (current <= max) { | |
await write(write_stream, current++) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment