diff --git a/lib/internal/fs/promises.js b/lib/internal/fs/promises.js index 2f95c4b79e17fd..fe629bc84cc35b 100644 --- a/lib/internal/fs/promises.js +++ b/lib/internal/fs/promises.js @@ -1240,7 +1240,35 @@ async function writeFile(path, data, options) { checkAborted(options.signal); - const fd = await open(path, flag, options.mode); + + let fd; + if (isCustomIterable(data) && typeof data.on === 'function') { + fd = await new Promise((resolve, reject) => { + let isRejected = false; + const onStreamError = (err) => { + isRejected = true; + reject(err); + }; + data.on('error', onStreamError); + open(path, flag, options.mode).then((fd) => { + data.removeListener('error', onStreamError); + if (isRejected) { + // If the stream emitted an error while opening the file, close the file. + // Ignore any errors from closing the file since the promise is already + // rejected with the stream error. + fd.close().then(undefined, () => {}); + } else { + resolve(fd); + } + }, (err) => { + data.removeListener('error', onStreamError); + reject(err); + }); + }); + } else { + fd = await open(path, flag, options.mode); + } + let writeOp = writeFileHandle(fd, data, options.signal, options.encoding); if (flush) { diff --git a/test/parallel/test-fs-promises-writefile.js b/test/parallel/test-fs-promises-writefile.js index 25df61b2b48414..542ac35e55edee 100644 --- a/test/parallel/test-fs-promises-writefile.js +++ b/test/parallel/test-fs-promises-writefile.js @@ -161,6 +161,21 @@ async function doReadWithEncoding() { assert.deepStrictEqual(data, syncData); } +async function doWriteStreamWithError() { + const s1 = new Readable({ + read() {} + }); + + process.nextTick(() => { + s1.emit('error', new Error('Boom')); + }); + + await assert.rejects( + fsPromises.writeFile(otherDest, s1), + { message: 'Boom' } + ); +} + (async () => { await doWrite(); await doWriteWithCancel(); @@ -169,6 +184,7 @@ async function doReadWithEncoding() { await doReadWithEncoding(); await doWriteStream(); await doWriteStreamWithCancel(); + await doWriteStreamWithError(); await doWriteIterable(); await doWriteInvalidIterable(); await doWriteIterableWithEncoding();