Skip to content

Instantly share code, notes, and snippets.

@stevenkaspar
Last active October 31, 2022 14:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevenkaspar/509f792cbf1194f9fb05e7d60a1fbc73 to your computer and use it in GitHub Desktop.
Save stevenkaspar/509f792cbf1194f9fb05e7d60a1fbc73 to your computer and use it in GitHub Desktop.
Nodejs - stream with 'drain' and async/await
// 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