Skip to content

Commit 4c51e71

Browse files
author
HiroyukiYagihashi
committed
fs: writeFile support AsyncIterable, Iterable & Stream as data argument
Fixes: #37391
1 parent 75cc41e commit 4c51e71

File tree

3 files changed

+91
-4
lines changed

3 files changed

+91
-4
lines changed

doc/api/fs.md

+5-1
Original file line numberDiff line numberDiff line change
@@ -3833,6 +3833,9 @@ details.
38333833
<!-- YAML
38343834
added: v0.1.29
38353835
changes:
3836+
- version: REPLACEME
3837+
pr-url: https://github.com/nodejs/node/pull/37490
3838+
description: The `data` argument supports `AsyncIterable`, `Iterable` & `Stream`.
38363839
- version: v15.2.0
38373840
pr-url: https://github.com/nodejs/node/pull/35993
38383841
description: The options argument may include an AbortSignal to abort an
@@ -3866,7 +3869,8 @@ changes:
38663869
-->
38673870
38683871
* `file` {string|Buffer|URL|integer} filename or file descriptor
3869-
* `data` {string|Buffer|TypedArray|DataView|Object}
3872+
* `data` {string|Buffer|TypedArray|DataView|Object|AsyncIterable|Iterable
3873+
|Stream}
38703874
* `options` {Object|string}
38713875
* `encoding` {string|null} **Default:** `'utf8'`
38723876
* `mode` {integer} **Default:** `0o666`

lib/internal/fs/promises.js

+32-3
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ const kReadFileMaxChunkSize = 2 ** 14;
1010
const kWriteFileMaxChunkSize = 2 ** 14;
1111

1212
const {
13+
ArrayIsArray,
1314
ArrayPrototypePush,
1415
Error,
1516
MathMax,
@@ -21,6 +22,8 @@ const {
2122
PromiseResolve,
2223
SafeArrayIterator,
2324
Symbol,
25+
SymbolAsyncIterator,
26+
SymbolIterator,
2427
Uint8Array,
2528
} = primordials;
2629

@@ -41,7 +44,7 @@ const {
4144
ERR_INVALID_ARG_VALUE,
4245
ERR_METHOD_NOT_IMPLEMENTED,
4346
} = codes;
44-
const { isArrayBufferView } = require('internal/util/types');
47+
const { isArrayBufferView, isTypedArray } = require('internal/util/types');
4548
const { rimrafPromises } = require('internal/fs/rimraf');
4649
const {
4750
copyObject,
@@ -273,7 +276,21 @@ async function fsCall(fn, handle, ...args) {
273276
}
274277

275278
async function writeFileHandle(filehandle, data, signal) {
276-
// `data` could be any kind of typed array.
279+
if (signal?.aborted) {
280+
throw lazyDOMException('The operation was aborted', 'AbortError');
281+
}
282+
if (isIterable(data)) {
283+
for await (const buf of data) {
284+
if (signal?.aborted) {
285+
throw lazyDOMException('The operation was aborted', 'AbortError');
286+
}
287+
await filehandle.write(buf);
288+
if (signal?.aborted) {
289+
throw lazyDOMException('The operation was aborted', 'AbortError');
290+
}
291+
}
292+
return;
293+
}
277294
data = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
278295
let remaining = data.length;
279296
if (remaining === 0) return;
@@ -663,7 +680,7 @@ async function writeFile(path, data, options) {
663680
options = getOptions(options, { encoding: 'utf8', mode: 0o666, flag: 'w' });
664681
const flag = options.flag || 'w';
665682

666-
if (!isArrayBufferView(data)) {
683+
if (!isArrayBufferView(data) && !isIterable(data)) {
667684
validateStringAfterArrayBufferView(data, 'data');
668685
data = Buffer.from(data, options.encoding || 'utf8');
669686
}
@@ -678,6 +695,18 @@ async function writeFile(path, data, options) {
678695
return PromisePrototypeFinally(writeFileHandle(fd, data), fd.close);
679696
}
680697

698+
function isIterable(obj) {
699+
if (obj == null) {
700+
return false;
701+
}
702+
703+
return SymbolAsyncIterator in obj || (
704+
SymbolIterator in obj &&
705+
typeof obj !== 'string' &&
706+
!ArrayIsArray(obj) &&
707+
!isTypedArray(obj));
708+
}
709+
681710
async function appendFile(path, data, options) {
682711
options = getOptions(options, { encoding: 'utf8', mode: 0o666, flag: 'a' });
683712
options = copyObject(options);

test/parallel/test-fs-promises-writefile.js

+54
Original file line numberDiff line numberDiff line change
@@ -7,20 +7,70 @@ const path = require('path');
77
const tmpdir = require('../common/tmpdir');
88
const assert = require('assert');
99
const tmpDir = tmpdir.path;
10+
const { Readable } = require('stream');
1011

1112
tmpdir.refresh();
1213

1314
const dest = path.resolve(tmpDir, 'tmp.txt');
1415
const otherDest = path.resolve(tmpDir, 'tmp-2.txt');
1516
const buffer = Buffer.from('abc'.repeat(1000));
1617
const buffer2 = Buffer.from('xyz'.repeat(1000));
18+
const stream = Readable.from(['a', 'b', 'c']);
19+
const stream2 = Readable.from(['a', 'b', 'c']);
20+
const iterable = {
21+
[Symbol.iterator]: function*() {
22+
yield 'a';
23+
yield 'b';
24+
yield 'c';
25+
}
26+
};
27+
const asyncIterable = {
28+
async* [Symbol.asyncIterator]() {
29+
yield 'a';
30+
yield 'b';
31+
yield 'c';
32+
}
33+
};
1734

1835
async function doWrite() {
1936
await fsPromises.writeFile(dest, buffer);
2037
const data = fs.readFileSync(dest);
2138
assert.deepStrictEqual(data, buffer);
2239
}
2340

41+
async function doWriteStream() {
42+
await fsPromises.writeFile(dest, stream);
43+
let expected = '';
44+
for await (const v of stream2) expected += v;
45+
const data = fs.readFileSync(dest, 'utf-8');
46+
assert.deepStrictEqual(data, expected);
47+
}
48+
49+
async function doWriteStreamWithCancel() {
50+
const controller = new AbortController();
51+
const { signal } = controller;
52+
process.nextTick(() => controller.abort());
53+
assert.rejects(fsPromises.writeFile(otherDest, stream, { signal }), {
54+
name: 'AbortError'
55+
});
56+
}
57+
58+
async function doWriteIterable() {
59+
await fsPromises.writeFile(dest, iterable);
60+
let expected = '';
61+
for await (const v of iterable) expected += v;
62+
const data = fs.readFileSync(dest, 'utf-8');
63+
assert.deepStrictEqual(data, expected);
64+
}
65+
66+
async function doWriteAsyncIterable() {
67+
await fsPromises.writeFile(dest, asyncIterable);
68+
let expected = '';
69+
for await (const v of asyncIterable) expected += v;
70+
const data = fs.readFileSync(dest, 'utf-8');
71+
assert.deepStrictEqual(data, expected);
72+
}
73+
2474
async function doWriteWithCancel() {
2575
const controller = new AbortController();
2676
const { signal } = controller;
@@ -55,4 +105,8 @@ doWrite()
55105
.then(doAppend)
56106
.then(doRead)
57107
.then(doReadWithEncoding)
108+
.then(doWriteStream)
109+
.then(doWriteStreamWithCancel)
110+
.then(doWriteIterable)
111+
.then(doWriteAsyncIterable)
58112
.then(common.mustCall());

0 commit comments

Comments
 (0)