Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 24 additions & 38 deletions src/js/node/fs.promises.ts
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,9 @@ const exports = {
access: asyncWrap(fs.access, "access"),
appendFile: async function (fileHandleOrFdOrPath, ...args) {
fileHandleOrFdOrPath = fileHandleOrFdOrPath?.[kFd] ?? fileHandleOrFdOrPath;
if (isCustomIterable(args[0])) {
return writeFileAsyncIterator(fileHandleOrFdOrPath, args[0], args[1], "a");
}
return _appendFile(fileHandleOrFdOrPath, ...args);
},
close: asyncWrap(fs.close, "close"),
Expand Down Expand Up @@ -311,15 +314,9 @@ const exports = {
},
writeFile: async function (fileHandleOrFdOrPath, ...args: any[]) {
fileHandleOrFdOrPath = fileHandleOrFdOrPath?.[kFd] ?? fileHandleOrFdOrPath;
if (
!$isTypedArrayView(args[0]) &&
typeof args[0] !== "string" &&
($isCallable(args[0]?.[Symbol.iterator]) || $isCallable(args[0]?.[Symbol.asyncIterator]))
) {
if (isCustomIterable(args[0])) {
$debug("fs.promises.writeFile async iterator slow path!");
// Node accepts an arbitrary async iterator here
// @ts-expect-error
return writeFileAsyncIterator(fileHandleOrFdOrPath, ...args);
return writeFileAsyncIterator(fileHandleOrFdOrPath, args[0], args[1], "w");
}
return _writeFile(fileHandleOrFdOrPath, ...args);
},
Expand Down Expand Up @@ -1571,7 +1568,6 @@ async function writeFileAsyncIteratorInner(fd, iterable, encoding, signal: Abort
const writer = Bun.file(fd).writer();

const mustRencode = !(encoding === "utf8" || encoding === "utf-8" || encoding === "binary" || encoding === "buffer");
let totalBytesWritten = 0;

try {
for await (let chunk of iterable) {
Expand All @@ -1588,49 +1584,48 @@ async function writeFileAsyncIteratorInner(fd, iterable, encoding, signal: Abort

const prom = writer.write(chunk);
if (prom && $isPromise(prom)) {
totalBytesWritten += await prom;
} else {
totalBytesWritten += prom;
await prom;
}
}
} finally {
await writer.end();
}

return totalBytesWritten;
}

// The only flag spellings whose `open` truncates. `r+` & co. overwrite in place,
// so resizing the file down to the bytes we wrote would destroy the rest of it.
function flagTruncates(flag): boolean {
return flag === "w" || flag === "w+" || flag === "wx" || flag === "wx+" || flag === "xw" || flag === "xw+";
// Strings and typed arrays are iterable too, but those take the native path.
function isCustomIterable(data): boolean {
return (
!$isTypedArrayView(data) &&
typeof data !== "string" &&
($isCallable(data?.[Symbol.iterator]) || $isCallable(data?.[Symbol.asyncIterator]))
);
}

async function writeFileAsyncIterator(fdOrPath, iterable, optionsOrEncoding, flag, mode) {
async function writeFileAsyncIterator(fdOrPath, iterable, optionsOrEncoding, defaultFlag: "w" | "a") {
let encoding;
let flag = defaultFlag;
let mode = 0o666;
let signal: AbortSignal | null = null;
if (typeof optionsOrEncoding === "object") {
encoding = optionsOrEncoding?.encoding ?? (encoding || "utf8");
flag = optionsOrEncoding?.flag ?? (flag || "w");
mode = optionsOrEncoding?.mode ?? (mode || 0o666);
encoding = optionsOrEncoding?.encoding ?? "utf8";
// Node: `options.flag || 'w'`, so an empty flag falls back to the default too.
flag = optionsOrEncoding?.flag || defaultFlag;
mode = optionsOrEncoding?.mode ?? mode;
signal = optionsOrEncoding?.signal ?? null;
if (signal?.aborted) {
throw $makeAbortError(undefined, { cause: signal.reason });
}
} else if (typeof optionsOrEncoding === "string" || optionsOrEncoding == null) {
encoding = optionsOrEncoding || "utf8";
flag ??= "w";
mode ??= 0o666;
}

if (!Buffer.isEncoding(encoding)) {
// ERR_INVALID_OPT_VALUE_ENCODING was removed in Node v15.
throw new TypeError(`Unknown encoding: ${encoding}`);
throw $ERR_INVALID_ARG_VALUE("encoding", encoding, "is invalid encoding");
}

let mustClose = typeof fdOrPath === "string";
// A FileHandle arrives here as its fd; anything else is a path for fs.open to open or reject.
const mustClose = typeof fdOrPath !== "number";
if (mustClose) {
// Rely on fs.open for further argument validaiton.
fdOrPath = await fs.open(fdOrPath, flag, mode);
}

Expand All @@ -1639,24 +1634,15 @@ async function writeFileAsyncIterator(fdOrPath, iterable, optionsOrEncoding, fla
throw $makeAbortError(undefined, { cause: signal.reason });
}

let totalBytesWritten = 0;

let error: Error | undefined;

try {
totalBytesWritten = await writeFileAsyncIteratorInner(fdOrPath, iterable, encoding, signal);
await writeFileAsyncIteratorInner(fdOrPath, iterable, encoding, signal);
} catch (err) {
error = err as Error;
}

// Handle cleanup outside of try-catch
if (mustClose) {
if (flagTruncates(flag)) {
try {
await fs.ftruncate(fdOrPath, totalBytesWritten);
} catch {}
}

await fs.close(fdOrPath);
}

Expand Down
Loading
Loading