Skip to content
Merged
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
3 changes: 3 additions & 0 deletions src/node/internal/filesystem.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ export function open(

export function close(fd: number): void;

export function tsStdio(): boolean;
export function stdioPrefix(fd: number): string;

export function write(
fd: number,
buffers: ArrayBufferView[],
Expand Down
6 changes: 5 additions & 1 deletion src/node/internal/internal_fs_callback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
// USE OR OTHER DEALINGS IN THE SOFTWARE.
import * as fssync from 'node-internal:internal_fs_sync';
import { default as cffs } from 'cloudflare-internal:filesystem';
import { isStdioFd, writeStdio } from 'node-internal:internal_fs_stdio';
import type {
FStatOptions,
MkdirTempSyncOptions,
Expand Down Expand Up @@ -1347,7 +1348,10 @@ export function writeFile(
} = validateWriteFileArgs(path, data, options);

callWithSingleArgCallback<number>(
() => cffs.writeAll(validatedPath, validatedData, { append, exclusive }),
() =>
isStdioFd(validatedPath)
? writeStdio(validatedPath, [validatedData])
: cffs.writeAll(validatedPath, validatedData, { append, exclusive }),
callback
);
}
Expand Down
113 changes: 113 additions & 0 deletions src/node/internal/internal_fs_stdio.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
// Copyright (c) 2026 Cloudflare, Inc.
// Licensed under the Apache 2.0 license found in the LICENSE file or at:
// https://opensource.org/licenses/Apache-2.0

// Writes to the stdio file descriptors (0, 1, 2) are line-buffered and logged
// through globalThis.console.log, which gives them inspector reporting and
// structured logging. Writes to stdin are discarded. Synchronous writes join
// into one line; a partial line is flushed in a microtask.

import { default as cffs } from 'cloudflare-internal:filesystem';

const MAX_WRITE_SIZE = 16 * 1024;
const MAX_LINE_BUFFER_SIZE = 4096;
const NEWLINE = 0x0a;

const decoder = new TextDecoder('utf-8', { ignoreBOM: true });

class StdioStream {
readonly #fd: number;
#pending: Uint8Array = new Uint8Array(0);
#scheduled = false;

constructor(fd: number) {
this.#fd = fd;
}

write(bytes: Uint8Array): void {
let pos = 0;
while (pos < bytes.length) {
const nl = bytes.indexOf(NEWLINE, pos);
if (nl === -1) {
this.#buffer(bytes.subarray(pos));
return;
}
const line = bytes.subarray(pos, nl);
pos = nl + 1;
if (this.#pending.length > 0) {
const head = this.#pending;
this.#pending = new Uint8Array(0);
this.#log(concat(head, line));
} else {
this.#log(line);
}
}
}

// Keeps the last MAX_LINE_BUFFER_SIZE bytes of the partial line.
#buffer(rest: Uint8Array): void {
const all = concat(this.#pending, rest);
this.#pending = all.subarray(
Math.max(0, all.length - MAX_LINE_BUFFER_SIZE)
);
if (this.#scheduled) return;
this.#scheduled = true;
queueMicrotask(() => {
this.#scheduled = false;
if (this.#pending.length === 0) return;
const line = this.#pending;
this.#pending = new Uint8Array(0);
this.#log(line);
});
}

#log(line: Uint8Array): void {
const console = globalThis.console as unknown;
if (typeof console !== 'object' || console === null) return;
const log = (console as { log?: unknown }).log;
if (typeof log !== 'function') return;
const prefix = cffs.stdioPrefix(this.#fd);
const text = decoder.decode(line);
let msg = text;
if (text.length === 0) msg = prefix;
else if (prefix.length > 0) msg = `${prefix} ${text}`;
log.call(console, msg);
}
}

function concat(a: Uint8Array, b: Uint8Array): Uint8Array {
const out = new Uint8Array(a.length + b.length);
out.set(a);
out.set(b, a.length);
return out;
}

const streams = [null, new StdioStream(1), new StdioStream(2)];

const enabled = cffs.tsStdio();

// When false, writes to the stdio file descriptors go to the native file
// system, which line-buffers and logs them itself.
export function isStdioFd(fd: number | URL): fd is number {
return enabled && (fd === 0 || fd === 1 || fd === 2);
}

// Returns the number of bytes accepted: each buffer is truncated to
// MAX_WRITE_SIZE.
export function writeStdio(
fd: number,
buffers: readonly NodeJS.ArrayBufferView[]
): number {
const chunks = buffers.map((b) => {
const n = Math.min(b.byteLength, MAX_WRITE_SIZE);
return n === 0
? new Uint8Array(0)
: new Uint8Array(b.buffer, b.byteOffset, n).slice();
});
let total = 0;
for (const chunk of chunks) {
streams[fd]?.write(chunk);
total += chunk.length;
}
return total;
}
3 changes: 3 additions & 0 deletions src/node/internal/internal_fs_sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ import {
} from 'node-internal:internal_fs_constants';
import { Dir, Dirent } from 'node-internal:internal_fs';
import { default as cffs } from 'cloudflare-internal:filesystem';
import { isStdioFd, writeStdio } from 'node-internal:internal_fs_stdio';

import { Buffer } from 'node-internal:internal_buffer';
import {
Expand Down Expand Up @@ -819,6 +820,7 @@ export function writeFileSync(
exclusive,
} = validateWriteFileArgs(path, data, options);

if (isStdioFd(validatedPath)) return writeStdio(validatedPath, [actualData]);
return cffs.writeAll(validatedPath, actualData, { append, exclusive });
}

Expand Down Expand Up @@ -851,6 +853,7 @@ export function writevSync(
return 0;
}

if (isStdioFd(fd)) return writeStdio(fd, buffers);
return cffs.write(fd, buffers, { position });
}

Expand Down
11 changes: 11 additions & 0 deletions src/workerd/api/filesystem.c++
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
#include <workerd/api/node/exceptions.h>
#include <workerd/api/streams/standard.h>
#include <workerd/io/features.h>
#include <workerd/io/worker.h>
#include <workerd/jsg/setup.h>
#include <workerd/util/autogate.h>

namespace workerd::api {

Expand Down Expand Up @@ -494,6 +496,15 @@ void FileSystemModule::close(jsg::Lock& js, int fd) {
vfs.closeFd(js, fd);
}

bool FileSystemModule::tsStdio() {
return util::Autogate::isEnabled(util::AutogateKey::TS_STDIO);
}

kj::StringPtr FileSystemModule::stdioPrefix(jsg::Lock& js, int fd) {
auto& isolate = Worker::Isolate::from(js);
return fd == 1 ? isolate.getStdoutPrefix() : isolate.getStderrPrefix();
}

uint32_t FileSystemModule::write(
jsg::Lock& js, int fd, kj::Array<jsg::JsRef<jsg::JsBufferSource>> data, WriteOptions options) {
auto& vfs = workerd::VirtualFileSystem::current(js);
Expand Down
8 changes: 8 additions & 0 deletions src/workerd/api/filesystem.h
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,12 @@ class FileSystemModule final: public jsg::Object {
int open(jsg::Lock& js, FilePath path, OpenOptions options);
void close(jsg::Lock& js, int fd);

// Whether writes to the stdio file descriptors are line-buffered and logged
// in TypeScript (the TS_STDIO autogate) rather than by StdioFile.
bool tsStdio();
// The logging prefix for stdout (fd 1) or stderr (fd 2).
kj::StringPtr stdioPrefix(jsg::Lock& js, int fd);

struct WriteOptions {
kj::Maybe<uint64_t> position;
JSG_STRUCT(position);
Expand Down Expand Up @@ -205,6 +211,8 @@ class FileSystemModule final: public jsg::Object {
JSG_METHOD(getFdHandle);
JSG_METHOD(cp);
JSG_METHOD(openAsBlob);
JSG_METHOD(tsStdio);
JSG_METHOD(stdioPrefix);
}

private:
Expand Down
55 changes: 55 additions & 0 deletions src/workerd/api/node/tests/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,25 @@ sh_test(
],
)

sh_test(
name = "process-stdio-sh-test@all-autogates",
srcs = ["test_process_stdio.sh"],
args = [
"$(location //src/workerd/server:workerd)",
"$(location process-stdio-nodejs-test.wd-test)",
"$(location process-stdio-nodejs-test.expected_stdout)",
"$(location process-stdio-nodejs-test.expected_stderr)",
"--all-autogates",
],
data = [
"process-stdio-nodejs-test.expected_stderr",
"process-stdio-nodejs-test.expected_stdout",
"process-stdio-nodejs-test.js",
"process-stdio-nodejs-test.wd-test",
"//src/workerd/server:workerd",
],
)

sh_test(
name = "process-stdio-fs-sh-test",
srcs = ["test_process_stdio.sh"],
Expand All @@ -383,6 +402,25 @@ sh_test(
],
)

sh_test(
name = "process-stdio-fs-sh-test@all-autogates",
srcs = ["test_process_stdio.sh"],
args = [
"$(location //src/workerd/server:workerd)",
"$(location process-stdio-fs-nodejs-test.wd-test)",
"$(location process-stdio-fs-nodejs-test.expected_stdout)",
"$(location process-stdio-fs-nodejs-test.expected_stderr)",
"--all-autogates",
],
data = [
"process-stdio-fs-nodejs-test.expected_stderr",
"process-stdio-fs-nodejs-test.expected_stdout",
"process-stdio-fs-nodejs-test.js",
"process-stdio-fs-nodejs-test.wd-test",
"//src/workerd/server:workerd",
],
)

wd_test(
src = "querystring-nodejs-test.wd-test",
args = ["--experimental"],
Expand Down Expand Up @@ -664,6 +702,23 @@ wd_test(
data = ["fs-access-test.js"],
)

# The stdio suite runs the same module under a C++ and a TypeScript cell. The
# C++ cell disables the @all-autogates variant: enabling every autogate enables
# TS_STDIO, which swaps in the TypeScript implementation under a cell whose
# USING_TS_IMPL binding says C++.
wd_test(
src = "fs-stdio-cpp.wd-test",
args = ["--experimental"],
data = ["fs-stdio-test.js"],
generate_all_autogates_variant = False,
)

wd_test(
src = "fs-stdio-ts.wd-test",
args = ["--experimental"],
data = ["fs-stdio-test.js"],
)

wd_test(
src = "fs-chown-chmod-test.wd-test",
args = ["--experimental"],
Expand Down
18 changes: 18 additions & 0 deletions src/workerd/api/node/tests/fs-stdio-cpp.wd-test
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using Workerd = import "/workerd/workerd.capnp";

# Runs fs-stdio-test.js against the C++ implementation
# (StdioFile in io/worker-fs.c++).

const unitTests :Workerd.Config = (
services = [
( name = "fs-stdio-cpp",
worker = (
modules = [
(name = "worker", esModule = embed "fs-stdio-test.js")
],
compatibilityFlags = ["nodejs_compat", "experimental", "enable_nodejs_fs_module"],
bindings = [(name = "USING_TS_IMPL", json = "false")],
)
),
],
);
Loading
Loading