Repository navigation
Add variant of fs.create{Read,Write}Stream to fs/promises #21342
Description
Activity
To clean up the resource, you should use finally, which can also address the problem when you throw an error.
Reacted by Claudia Meadows@simonkcleung This isn't about cleanup. It's about errors during initialization.
I would prefer this to be a chance to change the readable/writeable streams returned by fs module.
E.g. something like a
.promiseproperty on readable and writable streams that resolves onclosefor writeable andendfor readable and rejects onerror. #20909 is related.@ChALkeR I would be mildly okay with that, too, but I'd still like the
ready/errorissue also resolved. And yes, #20909 is one of the driving reasons for me filing this bug. (It's the most common case where I need that feature, and I've written a dedicated helper for this probably a few dozen times already.)Using this + your addition would convert this:
// Old with callbacks const input = fs.createWriteStream(infile) const output = fs.createWriteStream(outfile) let readyIn = false let readyOut = false input.on("error", error) output.on("error", error) input.on("ready", onReadyIn) output.on("ready", onReadyOut) input.on("close", close) output.on("close", close) output.on("finish", close) function onReadyIn() { readyIn = true if (readyOut) writeData() } function onReadyOut() { readyOut = true if (readyIn) writeData() } function error(e) { cleanup() if (readyIn) input.destroy(e) if (readyOut) output.destroy(e) } function close() { cleanup() if (readyIn) input.destroy() if (readyOut) output.destroy() } function cleanup() { input.removeListener("error", error) output.removeListener("error", error) input.removeListener("ready", onReadyIn) output.removeListener("ready", onReadyOut) }
to this:
// New with promises let input, output try { input = await fsPromises.createReadStream(infile) output = await fsPromises.createReadStream(outfile) // write data } finally { if (input != null) { input.destroy(); await input.closePromise } if (output != null) { output.destroy(); await output.closePromise } }
I don't like the name
.promise, though - it's too generic for that specific of a thing. It's also not FS-specific. Also, if you're going to do that, you may want to includeclosefor readable, too, since that's what fires when you.destroya readable stream.This is already possible given that a stream.Readable can be used as an async generator and a Promises version of fileHandle.write() exists. Closing.
Reacted by Claudia Meadows
Basically, I'd like to see those two common core APIs ported to use promises for the initial
ready/error.This amounts to the vast majority of my routine promise event wrappers while using
fs/promisesnormally.