Running an Nish program under Node

An Nish program is TypeScript, so a reasonable question is whether Node can just run it. The answer is yes, in f64 mode, within an overlap this page states exactly — and no in i32 mode, ever.

This page is about the prelude, runtime/nish.mjs: it supplies the globals Nish has and Node does not, and rewrites nothing. A prelude can only replace globals, never operators and never the object model, so it covers f64 mode minus the list below.

To run a program under Node exactly, in either mode, have the compiler translate it: --emit-ts <dir> sees the type of every expression, turns a + b into (a + b) | 0 where the type needs it, and writes TypeScript a person can keep, importing its builtins from nish/runtime, with nish/runtime/node or nish/runtime/browser as the host. The guide's Back to TypeScript covers it.

Using it

node --experimental-strip-types --import ./runtime/nish.mjs \
  -e 'const m = await import("./prog.ts"); const code = await m.main();
      await (await import("nish:async")).settleTasks(); process.exit(code)'

The -e is needed because an Nish program exports main rather than running anything at top level: node … prog.ts would load the module, never call main, print nothing and exit 0. The one-liner imports the module and calls main itself, which is what the native binary's entry point does, and exits with what main returns (0 for a main that returns void).

An async main answers a promise, so the one-liner awaits it, and then waits for every task spawn started (settleTasks, from nish:async as the hook answers it), as the native driver drains its queue before the process exits; for a plain main both are no-ops. The import path is resolved from the current directory, so keep the ./.

An async program runs on Node's own async/await, so its tasks resume in Node's order, not the native one: an await always yields to the microtask queue, and spawn(f(x)) runs f only to its first await, where the native build runs it until it first waits on the outside world. A program whose output depends on that interleaving (tests/cases/async_spawn) prints the same lines in another order; see the guide's Where it differs from Node.

The program must be an ES module to Node, which an Nish program always is — the language has import/export and no CommonJS at all. This package is "type": "module", so an in-tree .ts is read that way and examples/nbody.ts imports cleanly from the repository root. Under a package that says "type": "commonjs", Node reads a .ts as CommonJS and export function main is a syntax error before type stripping ever runs; put the program under a directory whose package.json says { "type": "module" }, or give it an .mts extension.

What the prelude supplies

Everything delegates to runtime/shim.mjs, the module the compiler's own differential tests run against, so the two cannot drift: a semantic fixed there is fixed here in the same commit. The shim is itself a layer over two modules: runtime/core.mjs, the host-agnostic builtins, which name no node: module, process or Buffer, and runtime/node.mjs, which installs Node as the core's host — its output, exit, arguments, files, environment, children and clocks. The command lines above stay as they are.

  • console.log / console.error — String(x) plus a newline on a synchronous write. Node's own console inspects, so it prints -0 where String(-0) is 0 and appends n to a BigInt; both would be wrong.
  • write, writeError, panic
  • readFileSync, readFileSyncOrNull, writeFileSync, appendFileSync, mkdirSync, isDirectorySync, readdirSync, spawnSync, spawnSyncTo, monotonicNanos, lstatOwnerModeSync, geteuid, isExecutableSync — globals in Nish, not imports from node:fs
  • readFileBytesSync — Array.from(fs.readFileSync(path)) in a try, a plain array of byte values or null, because a u8[] is a plain array here
  • dst.set(src, offset) — the one method a plain Array lacks, added to Array.prototype (non-enumerable, and only when nothing got there first) with TypedArray.prototype.set's copy-first meaning and the native slice out of range panic; fill needs nothing, since Array.prototype.fill already means what the language's does (Bulk writes)
  • String.fromBytes — added to Node's String, where JavaScript has no such static: the range of a byte array as one string, one UTF-16 unit per byte as String.fromCharCode makes them, with the native slice out of range panic for a range outside the array. ASCII agrees with a native run; a byte above 127 is the divergence fromCharCode already has
  • statMtimeSync — fs.statSync(path, { throwIfNoEntry: false })?.mtimeMs, or NaN, which is the native arithmetic exactly, so the digits agree
  • crypto.getRandomValues — Node's own takes only a typed array, so the prelude replaces it on Node's crypto with one that fills a plain array too (through a Uint8Array) and panics past 65,536 bytes with the native words; Date.now needs nothing, since Node's is the same floored wall clock (The host)
  • signalFd, readSignal — installed only to throw: Node tells its event loop about a signal, and a blocking read never lets the loop run, so there is no synchronous answer to give
  • netAddress, netLocalPort, tcpListen, tcpAccept, netRead, netWrite, netShutdown, netClose, tcpConnect, connectResult, udpBind, udpSendTo, udpRecvFrom, pollCreate, pollAdd, pollModify, pollRemove, pollWait, unixListen, unixListenMode, unixConnect, unixAccept, unixSocketPair, sendFd, recvFd, peerCredentials — installed only to throw, each naming itself: Node's sockets are ready only to its event loop, which a program that owns its loop never returns to (nish:net). A nish:net import does not resolve under Node at all, nor does any other nish: import but the three below; the globals are what the prelude can answer
  • isTerminal, terminalSize — tty.isatty(fd), and the columns and rows Node keeps for stdout, or for stderr when stdout is not a terminal, [-25, 0] when neither is: the native answers (nish:term)
  • readStdin, waitStdin, setRawMode — installed only to throw, each naming itself: Node reads stdin only to its event loop, as it does a socket, and its own raw mode turns Ctrl-C into a byte where the native one keeps it a signal
  • setTerminalRestore — installed only to throw too: its bytes go out from the native runtime's exit, panic and signal paths, which a Node process does not run. All six are globals, and the nish:term import resolves to them
  • getenv — process.env[name] ?? null, because Node answers undefined where the language has only null
  • realpathSync — fs.realpathSync in a try, because Node throws where the native realpath answers NULL (a missing path, a loop, a component that is not a directory); Node's answer is already absolute and normalised, which is what POSIX guarantees, so nothing has to normalise it
  • toI32, toI64, toF32, toF64, toU8…toU64, f64ToBits, bitsToF64
  • ctSelect, ctEq — the same bitwise answers, put back in range with >>> 0 over a u32 (a number) and BigInt.asUintN(64, …) over a u64 (a BigInt). A number mixed with a BigInt throws a TypeError, as BigInt arithmetic does. The answers agree with a native run; the timing does not, and nothing here claims it (Constant time)
  • secureZero — fills the array with zeros, as the native wipe does
  • uncheckedGet, uncheckedSet, wrappingAdd, wrappingSub, wrappingMul — as globals and as the nish:unsafe import, which the prelude resolves to them: a plain read and write, and | 0, Math.imul or BigInt.asIntN(64, …) for the wrap
  • nish:simd — resolved to runtime/core.mjs, where a vector is a fresh typed array of its lanes (Uint8Array, Int32Array, Float32Array, …), so a lane wraps or rounds as its type does; replace copies, and a load or a store checks the whole vector and panics with the native words (nish:simd)
  • nish:secret — resolved to runtime/shim.mjs, where a Secret is a plain wrapper and wipe zero-fills what it holds; the checker's rules about a Secret are not enforced under Node, and a zero-fill there promises nothing about copies the engine made
  • Ok, Err
  • parseInt, parseFloat — Nish's, whose deviations from JavaScript are documented rules
  • process.argv — reindexed so argv[0] is the program on both sides
  • Arena — no-ops, used() answering zero; arena() answers a disposable whose disposal does nothing
  • nish/<module> imports — resolved to std/<module>.ts beside the prelude, the way the compiler resolves them, so import { parallelReduce } from "nish/threads" runs as written. The standard library's bodies are the sequential meaning of each function and are what Node runs; they keep to the overlap below, which is why std/threads.ts computes a reduce's blocks in f64 rather than i64

A program that declares its own function of one of these names keeps it, the way a user function shadows a builtin in the compiler.

An arrow argument that reads a const of the function it is written in needs nothing from the prelude: under Node it is the JavaScript closure it reads as, and natively each name it reads is one more argument of a direct call. The two agree because the arrow runs during the call, on the same thread, and the checker refuses a capture that could change before it runs (a let) or that the arrow assigns (LANGUAGE.md; tests/cases/fnarg_capture_local runs on both).

What stays divergent

Each of these lives below the globals, in an operator or in the object model, so no prelude can reach it. They are language decisions (LANGUAGE.md), not gaps to fill.

  • i32 mode entirely. number is a 32-bit integer whose signed overflow panics; / truncates and panics on a zero divisor; >>> keeps the signed reading. Every arithmetic operator would have to change, which is what --emit-ts does.

  • s.length is UTF-16 units under Node and UTF-8 bytes natively, and so is every offset charCodeAt, substring and indexOf take or return. ASCII agrees; "héllo".length is 5 under Node and 6 natively. To count characters, codePointLength from nish/text answers 5 on both. It answers differently for text built from bytes, which is one unit per byte here (above): String.fromBytes of é's two bytes, or nish/json's decoding of "\u00e9", counts 1 natively and 2 under Node. It also answers differently for text that is not well-formed: a byte that is not UTF-8, such as String.fromCharCode(0x80), counts nothing natively and one unit under Node, and the two halves of a surrogate pair joined at run time are two lone surrogates natively and one pair under Node (tests/link/std_text_code_points_native pins both hosts' answers).

  • a[i] is unchecked. Out of range is undefined here and an exit-1 panic natively, and pop() on an empty array likewise. Only a program that goes out of range can tell the difference.

  • s.slice(a, b) clamps and takes negative indices here, and panics natively outside [0, length]: "abcdef".slice(2, 10) is cdef under Node and slice out of range: [2, 10) of length 6 natively, and slice(-2, 6) is ef against a panic. Unlike a[i], JavaScript defines both as correct, so a program ported from TypeScript can depend on them. substring keeps JavaScript's clamping exactly; slice is the checked, faster one.

  • A record put into an array is copied natively and shared here (Arrays of records are contiguous). After ps.push(p); p.x = 9, ps[0].x is still the old value natively and 9 under Node, and [p, p] is two records natively and one object twice here. The reverse also holds: after const r = ps[0]; ps[0] = q, r reads q's fields natively, because it points into the slot, and the old object under Node.

  • new Array<T>(n) has holes here. Natively it zero-fills, and under Node every slot is undefined until written, so a[1] + 1.0 is 1 natively and NaN here. A slot of a nish:simd vector array is the zero vector natively and undefined here, so extract(a[1], 0) is 0 natively and replace(a[1], 0, x) throws here. --emit-ts writes each of these as a zero-filled newArray, each vector slot its own zero typed array.

  • The typed-array names are plain arrays natively, without push and pop. Float64Array is f64[] in the language, and under Node it is JavaScript's fixed-length typed array. A receiver spelled with the name refuses push and pop at compile time (NL2415), so the TypeError: t.push is not a function a program could once reach here is a compile error natively too. A value the spelling does not reach — through another module's type alias, out of a Map or Set, or a generic's T result — still pushes natively and throws here (LANGUAGE.md).

  • A ranged integer is unchecked. integer<Lo, Hi> is an alias of number in runtime/nish.d.ts, so a value that leaves its range is silent here and an exit-1 panic natively (Type rules). Only a program that leaves a range can tell the difference.

  • orReturn() does not propagate. It throws a marker, and under the prelude nothing catches it, so it escapes as an uncaught exception. --emit-ts writes it as an early return instead. Every other part of Result works — Ok, Err, isOk, isErr, .value, .error, unwrapOr, expect.

  • Number(s) keeps JavaScript's parsing. Number is a constructor carrying statics (Number.isNaN among them) that both Node and the prelude itself need, so it is left alone; it differs from Nish's on the 0b and 0o prefixes.

  • Arena.used() reports zero, because there is no arena. A program printing it is measuring the native allocator by definition.

  • i64 and u64 are out, for the same reason i32 mode is. runtime/shim.mjs represents them as BigInt — the only JavaScript type that holds 64 bits and wraps where the native ones wrap — and unrewritten source writes n + 1, which JavaScript refuses to mix with a BigInt. So toI64, toU64 and f64ToBits throw a TypeError at the first arithmetic rather than answer something quietly wrong, which is the failure mode to want: a number that silently stopped wrapping at 2^53 would be much worse than a thrown error naming the line.

  • Node only. The prelude installs its loader with node:module's registerHooks, which Bun does not have (Export named 'registerHooks' not found), and runtime/node.mjs, the host the shim installs, imports node:fs, node:child_process and node:os, which a browser does not have. runtime/core.mjs imports none of them: another host is an adapter that installs itself in its place (Bun and other hosts).

  • A scope's tasks run at the spawn under Node, one after another, and each stores its answer there; natively they run together when the scope's block ends, and each answer is stored after the last task finishes (LANGUAGE.md). A task writes nothing another can see except through a Mutex's guard (the next item), and cannot print, and the checker refuses a program that reads a destination, or writes what a task may read, before the block ends, so the two print the same — for guarded writes, when they commute, as the next item says.

    s.spawn(entry, arg) and s.spawn(() => ...) reach the same spawn, which sees that no slot was written (an omitted argument is undefined, neither below zero nor at or above it) and runs the task with nothing to store; an arrow task's captures are the consts its closure reads, which cannot change. using itself needs --js-explicit-resource-management on Node 22 and is native from Node 24; Node 22's flagged using never calls [Symbol.dispose], and nothing here needs it to, because every task has run by the time the block ends.

  • A Mutex's lock waits for nothing under Node. lock() answers the guard at once and its [Symbol.dispose] does nothing, because the tasks run one at a time, at their spawns, so their critical sections run in spawn order — one of the orders the native threads can run them in (LANGUAGE.md).

    A program whose guarded updates commute exactly (integer sums and counts, a histogram, not an f64 sum) and whose tasks do not branch on what they read under the lock prints the same both ways; the checker refuses the parent locking what a scope's tasks share from the statement that holds the first spawn to the end of the block, where the two would differ. A store to g.value itself reaches the Mutex, because the guard is the Mutex's own storage.

  • A Channel is an array queue under Node. send pushes, and for (const x of ch) takes values off the front as it walks, through the channel's [Symbol.iterator], and ends when the queue is empty: so a loop that stops early leaves the rest for the next one, and a loop over a drained channel ends at once, as natively.

    Nothing waits, and nothing needs to: a task runs at its spawn, and the checker holds every task that may send on a channel to a spawn before the one receiver's, so every value has been sent when the receiver's loop starts (LANGUAGE.md). How two senders' values interleave is spawn order here and the scheduler's natively, so a program prints the same both ways when what it prints does not depend on that order — a count, an integer sum.

  • 1-ulp libm differences in sin/cos/log/pow (glibc vs V8's fdlibm).

How close it gets

The compiler's own tests run every f64-mode program in its corpus both ways and compare stdout and exit status, and the only programs that differ are the ones written to probe a decision in the list above (f64_libm, f64_minmax_nan, f64_round_negzero and f64_i32_mixed). An ordinary program does not look like them: examples/nbody.ts prints byte-identical output either way.