Skip to content

Commit 93ff28b

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

File tree

3 files changed

+94
-10
lines changed

3 files changed

+94
-10
lines changed

doc/api/fs.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -3866,7 +3866,8 @@ changes:
38663866
-->
38673867
38683868
* `file` {string|Buffer|URL|integer} filename or file descriptor
3869-
* `data` {string|Buffer|TypedArray|DataView|Object}
3869+
* `data` {string|Buffer|TypedArray|DataView|Object|AsyncIterable|Iterable
3870+
|Stream}
38703871
* `options` {Object|string}
38713872
* `encoding` {string|null} **Default:** `'utf8'`
38723873
* `mode` {integer} **Default:** `0o666`

lib/internal/fs/promises.js

+38-9
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ const {
2222
SafeArrayIterator,
2323
Symbol,
2424
Uint8Array,
25+
SymbolIterator,
26+
SymbolAsyncIterator
2527
} = primordials;
2628

2729
const {
@@ -663,19 +665,46 @@ async function writeFile(path, data, options) {
663665
options = getOptions(options, { encoding: 'utf8', mode: 0o666, flag: 'w' });
664666
const flag = options.flag || 'w';
665667

666-
if (!isArrayBufferView(data)) {
667-
validateStringAfterArrayBufferView(data, 'data');
668-
data = Buffer.from(data, options.encoding || 'utf8');
668+
if (isStream(data) || isIterable(data)) {
669+
const fd = await open(path, flag, options.mode);
670+
if (options.signal?.aborted) {
671+
throw lazyDOMException('The operation was aborted', 'AbortError');
672+
}
673+
try {
674+
for await (const buf of data) {
675+
await fd.write(buf);
676+
}
677+
} finally {
678+
await fd.close();
679+
}
680+
} else {
681+
if (!isArrayBufferView(data)) {
682+
validateStringAfterArrayBufferView(data, 'data');
683+
data = Buffer.from(data, options.encoding || 'utf8');
684+
}
685+
686+
if (path instanceof FileHandle) {
687+
return writeFileHandle(path, data, options.signal);
688+
}
689+
690+
const fd = await open(path, flag, options.mode);
691+
if (options.signal?.aborted) {
692+
throw lazyDOMException('The operation was aborted', 'AbortError');
693+
}
694+
return PromisePrototypeFinally(writeFileHandle(fd, data), fd.close);
669695
}
696+
}
670697

671-
if (path instanceof FileHandle)
672-
return writeFileHandle(path, data, options.signal);
698+
function isStream(obj) {
699+
return !!(obj && typeof obj.pipe === 'function');
700+
}
673701

674-
const fd = await open(path, flag, options.mode);
675-
if (options.signal?.aborted) {
676-
throw lazyDOMException('The operation was aborted', 'AbortError');
702+
function isIterable(obj) {
703+
if (!obj || typeof obj === 'string' || obj.buffer || Array.isArray(obj)) {
704+
return false;
677705
}
678-
return PromisePrototypeFinally(writeFileHandle(fd, data), fd.close);
706+
return typeof obj[Symbol.iterator] === 'function' ||
707+
typeof obj[Symbol.asyncIterator] === 'function';
679708
}
680709

681710
async function appendFile(path, data, 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)