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: #37391
  • Loading branch information
HiroyukiYagihashi committed Feb 23, 2021
1 parent 75cc41e commit 93ff28b
Show file tree
Hide file tree
Showing 3 changed files with 94 additions and 10 deletions.
3 changes: 2 additions & 1 deletion doc/api/fs.md
Expand Up @@ -3866,7 +3866,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: 38 additions & 9 deletions lib/internal/fs/promises.js
Expand Up @@ -22,6 +22,8 @@ const {
SafeArrayIterator,
Symbol,
Uint8Array,
SymbolIterator,
SymbolAsyncIterator
} = primordials;

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

if (!isArrayBufferView(data)) {
validateStringAfterArrayBufferView(data, 'data');
data = Buffer.from(data, options.encoding || 'utf8');
if (isStream(data) || isIterable(data)) {
const fd = await open(path, flag, options.mode);
if (options.signal?.aborted) {
throw lazyDOMException('The operation was aborted', 'AbortError');
}
try {
for await (const buf of data) {
await fd.write(buf);
}
} finally {
await fd.close();
}
} else {
if (!isArrayBufferView(data)) {
validateStringAfterArrayBufferView(data, 'data');
data = Buffer.from(data, options.encoding || 'utf8');
}

if (path instanceof FileHandle) {
return writeFileHandle(path, data, options.signal);
}

const fd = await open(path, flag, options.mode);
if (options.signal?.aborted) {
throw lazyDOMException('The operation was aborted', 'AbortError');
}
return PromisePrototypeFinally(writeFileHandle(fd, data), fd.close);
}
}

if (path instanceof FileHandle)
return writeFileHandle(path, data, options.signal);
function isStream(obj) {
return !!(obj && typeof obj.pipe === 'function');
}

const fd = await open(path, flag, options.mode);
if (options.signal?.aborted) {
throw lazyDOMException('The operation was aborted', 'AbortError');
function isIterable(obj) {
if (!obj || typeof obj === 'string' || obj.buffer || Array.isArray(obj)) {
return false;
}
return PromisePrototypeFinally(writeFileHandle(fd, data), fd.close);
return typeof obj[Symbol.iterator] === 'function' ||
typeof obj[Symbol.asyncIterator] === 'function';
}

async function appendFile(path, data, options) {
Expand Down
54 changes: 54 additions & 0 deletions test/parallel/test-fs-promises-writefile.js
Expand Up @@ -7,20 +7,70 @@ 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 stream2 = Readable.from(['a', 'b', 'c']);
const iterable = {
[Symbol.iterator]: function*() {
yield 'a';
yield 'b';
yield 'c';
}
};
const asyncIterable = {
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);
let expected = '';
for await (const v of stream2) expected += v;
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);
let expected = '';
for await (const v of iterable) expected += v;
const data = fs.readFileSync(dest, 'utf-8');
assert.deepStrictEqual(data, expected);
}

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

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

0 comments on commit 93ff28b

Please sign in to comment.