Skip to content

Instantly share code, notes, and snippets.

@jrc03c
Last active August 23, 2023 16:30
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 jrc03c/e6f79a83c9ca8fc80d8c6f088e8b724d to your computer and use it in GitHub Desktop.
Save jrc03c/e6f79a83c9ca8fc80d8c6f088e8b724d to your computer and use it in GitHub Desktop.
Stream (write) a file to disk in Node
const fs = require("fs")
!(async () => {
const stream = fs.createWriteStream("path/to/file")
let canWrite = true
let counter = 0
// optionally listen for errors
stream.on("error", error => {
throw error
})
// the `stream.write` function returns a boolean indicating whether or not the
// stream is ready to write more or not; and by listening for the "drain"
// event, we can know when it's ready to start writing again
stream.on("drain", () => {
canWrite = true
})
stream.on("end", () => {
stream.destroy()
})
const interval = setInterval(() => {
if (!canWrite) return
canWrite = stream.write(Math.random().toString() + "\n")
counter++
if (counter > 100) {
clearInterval(interval)
stream.end()
}
}, 10)
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment