Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fs: fix async iterator partial writes with writeFile #38615

Closed
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
13 changes: 10 additions & 3 deletions lib/internal/fs/promises.js
Original file line number Diff line number Diff line change
Expand Up @@ -296,9 +296,16 @@ async function writeFileHandle(filehandle, data, signal, encoding) {
if (isCustomIterable(data)) {
for await (const buf of data) {
checkAborted(signal);
await write(
filehandle, buf, undefined,
isArrayBufferView(buf) ? buf.byteLength : encoding);
const toWrite =
isArrayBufferView(buf) ? buf : Buffer.from(buf, encoding || 'utf8');
let remaining = toWrite.byteLength;
while (remaining > 0) {
checkAborted(signal);
const writeSize = MathMin(kWriteFileMaxChunkSize, remaining);
const { bytesWritten } = await write(
filehandle, toWrite, toWrite.byteLength - remaining, writeSize);
remaining -= bytesWritten;
}
checkAborted(signal);
Linkgoron marked this conversation as resolved.
Show resolved Hide resolved
}
return;
Expand Down
15 changes: 15 additions & 0 deletions test/parallel/test-fs-promises-writefile.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,14 @@ const iterable = {
yield 'c';
}
};

const veryLargeBuffer = {
expected: 'dogs running'.repeat(512 * 1024),
*[Symbol.iterator]() {
yield Buffer.from('dogs running'.repeat(512 * 1024), 'utf8');
}
};

function iterableWith(value) {
return {
*[Symbol.iterator]() {
Expand Down Expand Up @@ -106,6 +114,12 @@ async function doWriteAsyncIterable() {
assert.deepStrictEqual(data, asyncIterable.expected);
}

async function doWriteAsyncLargeIterable() {
await fsPromises.writeFile(dest, veryLargeBuffer);
const data = fs.readFileSync(dest, 'utf-8');
assert.deepStrictEqual(data, veryLargeBuffer.expected);
}

async function doWriteInvalidValues() {
await Promise.all(
[42, 42n, {}, Symbol('42'), true, undefined, null, NaN].map((value) =>
Expand Down Expand Up @@ -158,5 +172,6 @@ async function doReadWithEncoding() {
await doWriteIterableWithEncoding();
await doWriteBufferIterable();
await doWriteAsyncIterable();
await doWriteAsyncLargeIterable();
await doWriteInvalidValues();
})().then(common.mustCall());