Skip to content

Commit 99cfd5d

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

File tree

3 files changed

+95
-10
lines changed

3 files changed

+95
-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

+39-9
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,9 @@ const {
2222
SafeArrayIterator,
2323
Symbol,
2424
Uint8Array,
25+
SymbolIterator,
26+
SymbolAsyncIterator,
27+
ArrayIsArray
2528
} = primordials;
2629

2730
const {
@@ -663,19 +666,46 @@ async function writeFile(path, data, options) {
663666
options = getOptions(options, { encoding: 'utf8', mode: 0o666, flag: 'w' });
664667
const flag = options.flag || 'w';
665668

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

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

674-
const fd = await open(path, flag, options.mode);
675-
if (options.signal?.aborted) {
676-
throw lazyDOMException('The operation was aborted', 'AbortError');
703+
function isIterable(obj) {
704+
if (!obj || typeof obj === 'string' || obj.buffer || ArrayIsArray(obj)) {
705+
return false;
677706
}
678-
return PromisePrototypeFinally(writeFileHandle(fd, data), fd.close);
707+
return typeof obj[SymbolIterator] === 'function' ||
708+
typeof obj[SymbolAsyncIterator] === 'function';
679709
}
680710

681711
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)