Skip to content

Commit

Permalink
fs: writeFile support AsyncIterable, Iterable & Stream as `da…
Browse files Browse the repository at this point in the history
…ta` argument

Fixes: nodejs#37391
  • Loading branch information
HiroyukiYagihashi committed Mar 4, 2021
1 parent f6b1df2 commit 256c9a5
Show file tree
Hide file tree
Showing 4 changed files with 94 additions and 9 deletions.
6 changes: 5 additions & 1 deletion doc/api/fs.md
Original file line number Diff line number Diff line change
Expand Up @@ -1244,6 +1244,9 @@ All the [caveats][] for `fs.watch()` also apply to `fsPromises.watch()`.
<!-- YAML
added: v10.0.0
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/37490
description: The `data` argument supports `AsyncIterable`, `Iterable` & `Stream`.
- version: v15.2.0
pr-url: https://github.com/nodejs/node/pull/35993
description: The options argument may include an AbortSignal to abort an
Expand All @@ -1259,7 +1262,8 @@ changes:
-->
* `file` {string|Buffer|URL|FileHandle} filename or `FileHandle`
* `data` {string|Buffer|Uint8Array|Object}
* `data` {string|Buffer|Uint8Array|Object|AsyncIterable|Iterable
|Stream}
* `options` {Object|string}
* `encoding` {string|null} **Default:** `'utf8'`
* `mode` {integer} **Default:** `0o666`
Expand Down
34 changes: 27 additions & 7 deletions lib/internal/fs/promises.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ const {
ERR_INVALID_ARG_VALUE,
ERR_METHOD_NOT_IMPLEMENTED,
} = codes;
const { isArrayBufferView } = require('internal/util/types');
const { isArrayBuffer, isArrayBufferView } = require('internal/util/types');
const { rimrafPromises } = require('internal/fs/rimraf');
const {
copyObject,
Expand Down Expand Up @@ -76,6 +76,7 @@ const pathModule = require('path');
const { promisify } = require('internal/util');
const { EventEmitterMixin } = require('internal/event_target');
const { watch } = require('internal/fs/watchers');
const { isIterable } = require('internal/streams/utils');

const kHandle = Symbol('kHandle');
const kFd = Symbol('kFd');
Expand Down Expand Up @@ -273,8 +274,23 @@ async function fsCall(fn, handle, ...args) {
}
}

async function writeFileHandle(filehandle, data, signal) {
// `data` could be any kind of typed array.
async function writeFileHandle(filehandle, data, signal, encoding) {
if (signal?.aborted) {
throw lazyDOMException('The operation was aborted', 'AbortError');
}
if (isCustomIterable(data)) {
for await (const buf of data) {
if (signal?.aborted) {
throw lazyDOMException('The operation was aborted', 'AbortError');
}
await write(
filehandle, buf, 0, isArrayBuffer(buf) ? buf.length : encoding);
if (signal?.aborted) {
throw lazyDOMException('The operation was aborted', 'AbortError');
}
}
return;
}
data = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
let remaining = data.length;
if (remaining === 0) return;
Expand Down Expand Up @@ -664,22 +680,26 @@ async function writeFile(path, data, options) {
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(data, options.encoding || 'utf8');
}

validateAbortSignal(options.signal);
if (path instanceof FileHandle)
return writeFileHandle(path, data, options.signal);
return writeFileHandle(path, data, options.signal, options.encoding);

if (options.signal?.aborted) {
throw lazyDOMException('The operation was aborted', 'AbortError');
}

const fd = await open(path, flag, options.mode);
const { signal } = options;
return PromisePrototypeFinally(writeFileHandle(fd, data, signal), fd.close);
return PromisePrototypeFinally(
writeFileHandle(fd, data, options.signal, options.encoding), fd.close);
}

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

async function appendFile(path, data, options) {
Expand Down
2 changes: 1 addition & 1 deletion test/parallel/test-fs-append-file.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ const throwNextTick = (e) => { process.nextTick(() => { throw e; }); };
}

// Test that appendFile does not accept invalid data type (callback API).
[false, 5, {}, [], null, undefined].forEach(async (data) => {
[false, 5, {}, null, undefined].forEach(async (data) => {
const errObj = {
code: 'ERR_INVALID_ARG_TYPE',
message: /"data"|"buffer"/
Expand Down
61 changes: 61 additions & 0 deletions test/parallel/test-fs-promises-writefile.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,76 @@ const path = require('path');
const tmpdir = require('../common/tmpdir');
const assert = require('assert');
const tmpDir = tmpdir.path;
const { Readable } = require('stream');

tmpdir.refresh();

const dest = path.resolve(tmpDir, 'tmp.txt');
const otherDest = path.resolve(tmpDir, 'tmp-2.txt');
const buffer = Buffer.from('abc'.repeat(1000));
const buffer2 = Buffer.from('xyz'.repeat(1000));
const stream = Readable.from(['a', 'b', 'c']);
const iterable = {
expected: 'abc',
*[Symbol.iterator]() {
yield 'a';
yield 'b';
yield 'c';
}
};
const asyncIterable = {
expected: 'abc',
async* [Symbol.asyncIterator]() {
yield 'a';
yield 'b';
yield 'c';
}
};

async function doWrite() {
await fsPromises.writeFile(dest, buffer);
const data = fs.readFileSync(dest);
assert.deepStrictEqual(data, buffer);
}

async function doWriteStream() {
await fsPromises.writeFile(dest, stream);
const expected = 'abc';
const data = fs.readFileSync(dest, 'utf-8');
assert.deepStrictEqual(data, expected);
}

async function doWriteStreamWithCancel() {
const controller = new AbortController();
const { signal } = controller;
process.nextTick(() => controller.abort());
assert.rejects(fsPromises.writeFile(otherDest, stream, { signal }), {
name: 'AbortError'
});
}

async function doWriteIterable() {
await fsPromises.writeFile(dest, iterable);
const data = fs.readFileSync(dest, 'utf-8');
assert.deepStrictEqual(data, iterable.expected);
}

async function doWriteAsyncIterable() {
await fsPromises.writeFile(dest, asyncIterable);
const data = fs.readFileSync(dest, 'utf-8');
assert.deepStrictEqual(data, asyncIterable.expected);
}

async function doWriteInvalidValues() {
await Promise.all(
[42, 42n, {}, Symbol('42'), true, undefined, null, NaN].map((value) =>
assert.rejects(fsPromises.writeFile(dest, value), {
code: 'ERR_INVALID_ARG_TYPE',
})
)
);
}

async function doWriteWithCancel() {
const controller = new AbortController();
const { signal } = controller;
Expand Down Expand Up @@ -55,4 +111,9 @@ doWrite()
.then(doAppend)
.then(doRead)
.then(doReadWithEncoding)
.then(doWriteStream)
.then(doWriteStreamWithCancel)
.then(doWriteIterable)
.then(doWriteAsyncIterable)
.then(doWriteInvalidValues)
.then(common.mustCall());

0 comments on commit 256c9a5

Please sign in to comment.