Last active
August 23, 2023 16:30
-
-
Save jrc03c/e6f79a83c9ca8fc80d8c6f088e8b724d to your computer and use it in GitHub Desktop.
Stream (write) a file to disk in Node
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
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