Skip to content

Commit 675ffcd

Browse files
author
HiroyukiYagihashi
committed
fs: add support for async iterators to fs.writeFile
Fixes: #38075
1 parent 18e4f40 commit 675ffcd

File tree

3 files changed

+121
-9
lines changed

3 files changed

+121
-9
lines changed

doc/api/fs.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3915,7 +3915,8 @@ changes:
39153915
-->
39163916
39173917
* `file` {string|Buffer|URL|integer} filename or file descriptor
3918-
* `data` {string|Buffer|TypedArray|DataView|Object}
3918+
* `data` {string|Buffer|TypedArray|DataView|Object
3919+
|AsyncIterable|Iterable|Stream}
39193920
* `options` {Object|string}
39203921
* `encoding` {string|null} **Default:** `'utf8'`
39213922
* `mode` {integer} **Default:** `0o666`

lib/fs.js

Lines changed: 39 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ const {
8585
const { FSReqCallback } = binding;
8686
const { toPathIfFileURL } = require('internal/url');
8787
const internalUtil = require('internal/util');
88+
const { isIterable } = require('internal/streams/utils');
8889
const {
8990
constants: {
9091
kIoMaxLength,
@@ -828,12 +829,12 @@ function write(fd, buffer, offset, length, position, callback) {
828829
} else {
829830
position = length;
830831
}
831-
length = 'utf8';
832+
length = length || 'utf8';
832833
}
833834

834835
const str = String(buffer);
835836
validateEncoding(str, length);
836-
callback = maybeCallback(position);
837+
callback = maybeCallback(callback || position);
837838

838839
const req = new FSReqCallback();
839840
req.oncomplete = wrapper;
@@ -2039,7 +2040,8 @@ function lutimesSync(path, atime, mtime) {
20392040
handleErrorFromBinding(ctx);
20402041
}
20412042

2042-
function writeAll(fd, isUserFd, buffer, offset, length, signal, callback) {
2043+
function writeAll(
2044+
fd, isUserFd, buffer, offset, length, signal, encoding, callback) {
20432045
if (signal?.aborted) {
20442046
const abortError = new AbortError();
20452047
if (isUserFd) {
@@ -2051,7 +2053,29 @@ function writeAll(fd, isUserFd, buffer, offset, length, signal, callback) {
20512053
}
20522054
return;
20532055
}
2054-
// write(fd, buffer, offset, length, position, callback)
2056+
if (isCustomIterable(buffer)) {
2057+
(async () => {
2058+
for await (const buf of buffer) {
2059+
fs.write(
2060+
fd, buf, undefined,
2061+
isArrayBufferView(buf) ? buf.byteLength : encoding,
2062+
null, (writeErr, _) => {
2063+
if (writeErr) {
2064+
if (isUserFd) {
2065+
callback(writeErr);
2066+
} else {
2067+
fs.close(fd, (err) => {
2068+
callback(aggregateTwoErrors(err, writeErr));
2069+
});
2070+
}
2071+
}
2072+
}
2073+
);
2074+
}
2075+
fs.close(fd, callback);
2076+
})();
2077+
return;
2078+
}
20552079
fs.write(fd, buffer, offset, length, null, (writeErr, written) => {
20562080
if (writeErr) {
20572081
if (isUserFd) {
@@ -2070,11 +2094,16 @@ function writeAll(fd, isUserFd, buffer, offset, length, signal, callback) {
20702094
} else {
20712095
offset += written;
20722096
length -= written;
2073-
writeAll(fd, isUserFd, buffer, offset, length, signal, callback);
2097+
writeAll(
2098+
fd, isUserFd, buffer, offset, length, signal, encoding, callback);
20742099
}
20752100
});
20762101
}
20772102

2103+
function isCustomIterable(obj) {
2104+
return isIterable(obj) && !isArrayBufferView(obj) && typeof obj !== 'string';
2105+
}
2106+
20782107
/**
20792108
* Asynchronously writes data to the file.
20802109
* @param {string | Buffer | URL | number} path
@@ -2093,15 +2122,16 @@ function writeFile(path, data, options, callback) {
20932122
options = getOptions(options, { encoding: 'utf8', mode: 0o666, flag: 'w' });
20942123
const flag = options.flag || 'w';
20952124

2096-
if (!isArrayBufferView(data)) {
2125+
if (!isArrayBufferView(data) && !isCustomIterable(data)) {
20972126
validateStringAfterArrayBufferView(data, 'data');
20982127
data = Buffer.from(String(data), options.encoding || 'utf8');
20992128
}
21002129

21012130
if (isFd(path)) {
21022131
const isUserFd = true;
21032132
const signal = options.signal;
2104-
writeAll(path, isUserFd, data, 0, data.byteLength, signal, callback);
2133+
writeAll(path, isUserFd, data,
2134+
0, data.byteLength, signal, options.encoding, callback);
21052135
return;
21062136
}
21072137

@@ -2114,7 +2144,8 @@ function writeFile(path, data, options, callback) {
21142144
} else {
21152145
const isUserFd = false;
21162146
const signal = options.signal;
2117-
writeAll(fd, isUserFd, data, 0, data.byteLength, signal, callback);
2147+
writeAll(fd, isUserFd, data,
2148+
0, data.byteLength, signal, options.encoding, callback);
21182149
}
21192150
});
21202151
}

test/parallel/test-fs-write-file.js

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ const common = require('../common');
2424
const assert = require('assert');
2525
const fs = require('fs');
2626
const join = require('path').join;
27+
const { Readable } = require('stream');
2728

2829
const tmpdir = require('../common/tmpdir');
2930
tmpdir.refresh();
@@ -95,3 +96,82 @@ fs.open(filename4, 'w+', common.mustSucceed((fd) => {
9596

9697
process.nextTick(() => controller.abort());
9798
}
99+
100+
{
101+
const filenameIterable = join(tmpdir.path, 'testIterable.txt');
102+
const iterable = {
103+
expected: 'abc',
104+
*[Symbol.iterator]() {
105+
yield 'a';
106+
yield 'b';
107+
yield 'c';
108+
}
109+
};
110+
111+
fs.writeFile(filenameIterable, iterable, common.mustSucceed(() => {
112+
const data = fs.readFileSync(filenameIterable, 'utf-8');
113+
assert.strictEqual(iterable.expected, data);
114+
}));
115+
}
116+
117+
{
118+
const filenameBufferIterable = join(tmpdir.path, 'testBufferIterable.txt');
119+
const bufferIterable = {
120+
expected: 'abc',
121+
*[Symbol.iterator]() {
122+
yield Buffer.from('a');
123+
yield Buffer.from('b');
124+
yield Buffer.from('c');
125+
}
126+
};
127+
128+
fs.writeFile(
129+
filenameBufferIterable, bufferIterable, common.mustSucceed(() => {
130+
const data = fs.readFileSync(filenameBufferIterable, 'utf-8');
131+
assert.strictEqual(bufferIterable.expected, data);
132+
})
133+
);
134+
}
135+
136+
137+
{
138+
const filenameAsyncIterable = join(tmpdir.path, 'testAsyncIterable.txt');
139+
const asyncIterable = {
140+
expected: 'abc',
141+
*[Symbol.asyncIterator]() {
142+
yield 'a';
143+
yield 'b';
144+
yield 'c';
145+
}
146+
};
147+
148+
fs.writeFile(filenameAsyncIterable, asyncIterable, common.mustSucceed(() => {
149+
const data = fs.readFileSync(filenameAsyncIterable, 'utf-8');
150+
assert.strictEqual(asyncIterable.expected, data);
151+
}));
152+
}
153+
154+
{
155+
const filenameStream = join(tmpdir.path, 'testStream.txt');
156+
const stream = Readable.from(['a', 'b', 'c']);
157+
const expected = 'abc';
158+
159+
fs.writeFile(filenameStream, stream, common.mustSucceed(() => {
160+
const data = fs.readFileSync(filenameStream, 'utf-8');
161+
assert.strictEqual(expected, data);
162+
}));
163+
}
164+
165+
{
166+
const filenameStreamWithEncoding =
167+
join(tmpdir.path, 'testStreamWithEncoding.txt');
168+
const stream = Readable.from(['ümlaut', ' ', 'sechzig']);
169+
const expected = 'ümlaut sechzig';
170+
171+
fs.writeFile(
172+
filenameStreamWithEncoding, stream, 'latin1', common.mustSucceed(() => {
173+
const data = fs.readFileSync(filenameStreamWithEncoding, 'latin1');
174+
assert.strictEqual(expected, data);
175+
})
176+
);
177+
}

0 commit comments

Comments
 (0)