Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 29 additions & 1 deletion lib/internal/fs/promises.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
16 changes: 16 additions & 0 deletions test/parallel/test-fs-promises-writefile.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -169,6 +184,7 @@ async function doReadWithEncoding() {
await doReadWithEncoding();
await doWriteStream();
await doWriteStreamWithCancel();
await doWriteStreamWithError();
await doWriteIterable();
await doWriteInvalidIterable();
await doWriteIterableWithEncoding();
Expand Down
Loading