Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit b9d7b46

Browse files
author
HiroyukiYagihashi
committedMar 3, 2021
fs: writeFile support AsyncIterable, Iterable & Stream as data argument
Fixes: nodejs#37391
1 parent f6b1df2 commit b9d7b46

File tree

4 files changed

+88
-4
lines changed

4 files changed

+88
-4
lines changed
 

‎doc/api/fs.md

+5-1
Original file line numberDiff line numberDiff line change
@@ -1244,6 +1244,9 @@ All the [caveats][] for `fs.watch()` also apply to `fsPromises.watch()`.
12441244
<!-- YAML
12451245
added: v10.0.0
12461246
changes:
1247+
- version: REPLACEME
1248+
pr-url: https://github.com/nodejs/node/pull/37490
1249+
description: The `data` argument supports `AsyncIterable`, `Iterable` & `Stream`.
12471250
- version: v15.2.0
12481251
pr-url: https://github.com/nodejs/node/pull/35993
12491252
description: The options argument may include an AbortSignal to abort an
@@ -1259,7 +1262,8 @@ changes:
12591262
-->
12601263
12611264
* `file` {string|Buffer|URL|FileHandle} filename or `FileHandle`
1262-
* `data` {string|Buffer|Uint8Array|Object}
1265+
* `data` {string|Buffer|Uint8Array|Object|AsyncIterable|Iterable
1266+
|Stream}
12631267
* `options` {Object|string}
12641268
* `encoding` {string|null} **Default:** `'utf8'`
12651269
* `mode` {integer} **Default:** `0o666`

‎lib/internal/fs/promises.js

+21-2
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ const pathModule = require('path');
7676
const { promisify } = require('internal/util');
7777
const { EventEmitterMixin } = require('internal/event_target');
7878
const { watch } = require('internal/fs/watchers');
79+
const { isIterable } = require('internal/streams/utils');
7980

8081
const kHandle = Symbol('kHandle');
8182
const kFd = Symbol('kFd');
@@ -274,7 +275,21 @@ async function fsCall(fn, handle, ...args) {
274275
}
275276

276277
async function writeFileHandle(filehandle, data, signal) {
277-
// `data` could be any kind of typed array.
278+
if (signal?.aborted) {
279+
throw lazyDOMException('The operation was aborted', 'AbortError');
280+
}
281+
if (isCustomIterable(data)) {
282+
for await (const buf of data) {
283+
if (signal?.aborted) {
284+
throw lazyDOMException('The operation was aborted', 'AbortError');
285+
}
286+
await filehandle.write(buf);
287+
if (signal?.aborted) {
288+
throw lazyDOMException('The operation was aborted', 'AbortError');
289+
}
290+
}
291+
return;
292+
}
278293
data = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
279294
let remaining = data.length;
280295
if (remaining === 0) return;
@@ -664,7 +679,7 @@ async function writeFile(path, data, options) {
664679
options = getOptions(options, { encoding: 'utf8', mode: 0o666, flag: 'w' });
665680
const flag = options.flag || 'w';
666681

667-
if (!isArrayBufferView(data)) {
682+
if (!isArrayBufferView(data) && !isCustomIterable(data)) {
668683
validateStringAfterArrayBufferView(data, 'data');
669684
data = Buffer.from(data, options.encoding || 'utf8');
670685
}
@@ -682,6 +697,10 @@ async function writeFile(path, data, options) {
682697
return PromisePrototypeFinally(writeFileHandle(fd, data, signal), fd.close);
683698
}
684699

700+
function isCustomIterable(obj) {
701+
return isIterable(obj) && !isArrayBufferView(obj) && typeof obj !== 'string';
702+
}
703+
685704
async function appendFile(path, data, options) {
686705
options = getOptions(options, { encoding: 'utf8', mode: 0o666, flag: 'a' });
687706
options = copyObject(options);

‎test/parallel/test-fs-append-file.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ const throwNextTick = (e) => { process.nextTick(() => { throw e; }); };
121121
}
122122

123123
// Test that appendFile does not accept invalid data type (callback API).
124-
[false, 5, {}, [], null, undefined].forEach(async (data) => {
124+
[false, 5, {}, null, undefined].forEach(async (data) => {
125125
const errObj = {
126126
code: 'ERR_INVALID_ARG_TYPE',
127127
message: /"data"|"buffer"/

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

+61
Original file line numberDiff line numberDiff line change
@@ -7,20 +7,76 @@ 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 iterable = {
20+
expected: 'abc',
21+
*[Symbol.iterator]() {
22+
yield 'a';
23+
yield 'b';
24+
yield 'c';
25+
}
26+
};
27+
const asyncIterable = {
28+
expected: 'abc',
29+
async* [Symbol.asyncIterator]() {
30+
yield 'a';
31+
yield 'b';
32+
yield 'c';
33+
}
34+
};
1735

1836
async function doWrite() {
1937
await fsPromises.writeFile(dest, buffer);
2038
const data = fs.readFileSync(dest);
2139
assert.deepStrictEqual(data, buffer);
2240
}
2341

42+
async function doWriteStream() {
43+
await fsPromises.writeFile(dest, stream);
44+
const expected = 'abc';
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+
const data = fs.readFileSync(dest, 'utf-8');
61+
assert.deepStrictEqual(data, iterable.expected);
62+
}
63+
64+
async function doWriteAsyncIterable() {
65+
await fsPromises.writeFile(dest, asyncIterable);
66+
const data = fs.readFileSync(dest, 'utf-8');
67+
assert.deepStrictEqual(data, asyncIterable.expected);
68+
}
69+
70+
async function doWriteInvalidValues() {
71+
await Promise.all(
72+
[42, 42n, {}, Symbol('42'), true, undefined, null, NaN].map((value) =>
73+
assert.rejects(fsPromises.writeFile(dest, value), {
74+
code: 'ERR_INVALID_ARG_TYPE',
75+
})
76+
)
77+
);
78+
}
79+
2480
async function doWriteWithCancel() {
2581
const controller = new AbortController();
2682
const { signal } = controller;
@@ -55,4 +111,9 @@ doWrite()
55111
.then(doAppend)
56112
.then(doRead)
57113
.then(doReadWithEncoding)
114+
.then(doWriteStream)
115+
.then(doWriteStreamWithCancel)
116+
.then(doWriteIterable)
117+
.then(doWriteAsyncIterable)
118+
.then(doWriteInvalidValues)
58119
.then(common.mustCall());

0 commit comments

Comments
 (0)
Please sign in to comment.