Skip to content

Commit

Permalink
fs: add support for async iterators to fs.writeFile
Browse files Browse the repository at this point in the history
  • Loading branch information
HiroyukiYagihashi committed May 3, 2021
1 parent 18e4f40 commit 675ffcd
Show file tree
Hide file tree
Showing 3 changed files with 121 additions and 9 deletions.
3 changes: 2 additions & 1 deletion doc/api/fs.md
Original file line number Diff line number Diff line change
Expand Up @@ -3915,7 +3915,8 @@ changes:
-->
* `file` {string|Buffer|URL|integer} filename or file descriptor
* `data` {string|Buffer|TypedArray|DataView|Object}
* `data` {string|Buffer|TypedArray|DataView|Object
|AsyncIterable|Iterable|Stream}
* `options` {Object|string}
* `encoding` {string|null} **Default:** `'utf8'`
* `mode` {integer} **Default:** `0o666`
Expand Down
47 changes: 39 additions & 8 deletions lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ const {
const { FSReqCallback } = binding;
const { toPathIfFileURL } = require('internal/url');
const internalUtil = require('internal/util');
const { isIterable } = require('internal/streams/utils');
const {
constants: {
kIoMaxLength,
Expand Down Expand Up @@ -828,12 +829,12 @@ function write(fd, buffer, offset, length, position, callback) {
} else {
position = length;
}
length = 'utf8';
length = length || 'utf8';
}

const str = String(buffer);
validateEncoding(str, length);
callback = maybeCallback(position);
callback = maybeCallback(callback || position);

const req = new FSReqCallback();
req.oncomplete = wrapper;
Expand Down Expand Up @@ -2039,7 +2040,8 @@ function lutimesSync(path, atime, mtime) {
handleErrorFromBinding(ctx);
}

function writeAll(fd, isUserFd, buffer, offset, length, signal, callback) {
function writeAll(
fd, isUserFd, buffer, offset, length, signal, encoding, callback) {
if (signal?.aborted) {
const abortError = new AbortError();
if (isUserFd) {
Expand All @@ -2051,7 +2053,29 @@ function writeAll(fd, isUserFd, buffer, offset, length, signal, callback) {
}
return;
}
// write(fd, buffer, offset, length, position, callback)
if (isCustomIterable(buffer)) {
(async () => {
for await (const buf of buffer) {
fs.write(
fd, buf, undefined,
isArrayBufferView(buf) ? buf.byteLength : encoding,
null, (writeErr, _) => {
if (writeErr) {
if (isUserFd) {
callback(writeErr);
} else {
fs.close(fd, (err) => {
callback(aggregateTwoErrors(err, writeErr));
});
}
}
}
);
}
fs.close(fd, callback);
})();
return;
}
fs.write(fd, buffer, offset, length, null, (writeErr, written) => {
if (writeErr) {
if (isUserFd) {
Expand All @@ -2070,11 +2094,16 @@ function writeAll(fd, isUserFd, buffer, offset, length, signal, callback) {
} else {
offset += written;
length -= written;
writeAll(fd, isUserFd, buffer, offset, length, signal, callback);
writeAll(
fd, isUserFd, buffer, offset, length, signal, encoding, callback);
}
});
}

function isCustomIterable(obj) {
return isIterable(obj) && !isArrayBufferView(obj) && typeof obj !== 'string';
}

/**
* Asynchronously writes data to the file.
* @param {string | Buffer | URL | number} path
Expand All @@ -2093,15 +2122,16 @@ function writeFile(path, data, options, callback) {
options = getOptions(options, { encoding: 'utf8', mode: 0o666, flag: 'w' });
const flag = options.flag || 'w';

if (!isArrayBufferView(data)) {
if (!isArrayBufferView(data) && !isCustomIterable(data)) {
validateStringAfterArrayBufferView(data, 'data');
data = Buffer.from(String(data), options.encoding || 'utf8');
}

if (isFd(path)) {
const isUserFd = true;
const signal = options.signal;
writeAll(path, isUserFd, data, 0, data.byteLength, signal, callback);
writeAll(path, isUserFd, data,
0, data.byteLength, signal, options.encoding, callback);
return;
}

Expand All @@ -2114,7 +2144,8 @@ function writeFile(path, data, options, callback) {
} else {
const isUserFd = false;
const signal = options.signal;
writeAll(fd, isUserFd, data, 0, data.byteLength, signal, callback);
writeAll(fd, isUserFd, data,
0, data.byteLength, signal, options.encoding, callback);
}
});
}
Expand Down
80 changes: 80 additions & 0 deletions test/parallel/test-fs-write-file.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const common = require('../common');
const assert = require('assert');
const fs = require('fs');
const join = require('path').join;
const { Readable } = require('stream');

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

process.nextTick(() => controller.abort());
}

{
const filenameIterable = join(tmpdir.path, 'testIterable.txt');
const iterable = {
expected: 'abc',
*[Symbol.iterator]() {
yield 'a';
yield 'b';
yield 'c';
}
};

fs.writeFile(filenameIterable, iterable, common.mustSucceed(() => {
const data = fs.readFileSync(filenameIterable, 'utf-8');
assert.strictEqual(iterable.expected, data);
}));
}

{
const filenameBufferIterable = join(tmpdir.path, 'testBufferIterable.txt');
const bufferIterable = {
expected: 'abc',
*[Symbol.iterator]() {
yield Buffer.from('a');
yield Buffer.from('b');
yield Buffer.from('c');
}
};

fs.writeFile(
filenameBufferIterable, bufferIterable, common.mustSucceed(() => {
const data = fs.readFileSync(filenameBufferIterable, 'utf-8');
assert.strictEqual(bufferIterable.expected, data);
})
);
}


{
const filenameAsyncIterable = join(tmpdir.path, 'testAsyncIterable.txt');
const asyncIterable = {
expected: 'abc',
*[Symbol.asyncIterator]() {
yield 'a';
yield 'b';
yield 'c';
}
};

fs.writeFile(filenameAsyncIterable, asyncIterable, common.mustSucceed(() => {
const data = fs.readFileSync(filenameAsyncIterable, 'utf-8');
assert.strictEqual(asyncIterable.expected, data);
}));
}

{
const filenameStream = join(tmpdir.path, 'testStream.txt');
const stream = Readable.from(['a', 'b', 'c']);
const expected = 'abc';

fs.writeFile(filenameStream, stream, common.mustSucceed(() => {
const data = fs.readFileSync(filenameStream, 'utf-8');
assert.strictEqual(expected, data);
}));
}

{
const filenameStreamWithEncoding =
join(tmpdir.path, 'testStreamWithEncoding.txt');
const stream = Readable.from(['ümlaut', ' ', 'sechzig']);
const expected = 'ümlaut sechzig';

fs.writeFile(
filenameStreamWithEncoding, stream, 'latin1', common.mustSucceed(() => {
const data = fs.readFileSync(filenameStreamWithEncoding, 'latin1');
assert.strictEqual(expected, data);
})
);
}

0 comments on commit 675ffcd

Please sign in to comment.