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-0whereString(-0)is0and appendsnto 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 fromnode:fs -
readFileBytesSync—Array.from(fs.readFileSync(path))in atry, a plain array of byte values ornull, because au8[]is a plain array here -
dst.set(src, offset)— the one method a plainArraylacks, added toArray.prototype(non-enumerable, and only when nothing got there first) withTypedArray.prototype.set's copy-first meaning and the nativeslice out of rangepanic;fillneeds nothing, sinceArray.prototype.fillalready means what the language's does (Bulk writes) -
String.fromBytes— added to Node'sString, where JavaScript has no such static: the range of a byte array as one string, one UTF-16 unit per byte asString.fromCharCodemakes them, with the nativeslice out of rangepanic for a range outside the array. ASCII agrees with a native run; a byte above 127 is the divergencefromCharCodealready 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'scryptowith one that fills a plain array too (through aUint8Array) and panics past 65,536 bytes with the native words;Date.nowneeds 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). Anish:netimport does not resolve under Node at all, nor does any othernish:import but the three below; the globals are what the prelude can answer -
isTerminal,terminalSize—tty.isatty(fd), and thecolumnsandrowsNode 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 thenish:termimport resolves to them -
getenv—process.env[name] ?? null, because Node answersundefinedwhere the language has onlynull -
realpathSync—fs.realpathSyncin atry, because Node throws where the nativerealpathanswers 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>>> 0over au32(anumber) andBigInt.asUintN(64, …)over au64(a BigInt). Anumbermixed with a BigInt throws aTypeError, 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 thenish:unsafeimport, which the prelude resolves to them: a plain read and write, and| 0,Math.imulorBigInt.asIntN(64, …)for the wrap -
nish:simd— resolved toruntime/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;replacecopies, and a load or a store checks the whole vector and panics with the native words (nish:simd) -
nish:secret— resolved toruntime/shim.mjs, where aSecretis a plain wrapper andwipezero-fills what it holds; the checker's rules about aSecretare 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 soargv[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 tostd/<module>.tsbeside the prelude, the way the compiler resolves them, soimport { 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 whystd/threads.tscomputes a reduce's blocks inf64rather thani64
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.
numberis 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-tsdoes. -
s.lengthis UTF-16 units under Node and UTF-8 bytes natively, and so is every offsetcharCodeAt,substringandindexOftake or return. ASCII agrees;"héllo".lengthis5under Node and6natively. To count characters,codePointLengthfromnish/textanswers5on both. It answers differently for text built from bytes, which is one unit per byte here (above):String.fromBytesofé's two bytes, ornish/json's decoding of"\u00e9", counts1natively and2under Node. It also answers differently for text that is not well-formed: a byte that is not UTF-8, such asString.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_nativepins both hosts' answers). -
a[i]is unchecked. Out of range isundefinedhere and an exit-1 panic natively, andpop()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)iscdefunder Node andslice out of range: [2, 10) of length 6natively, andslice(-2, 6)isefagainst a panic. Unlikea[i], JavaScript defines both as correct, so a program ported from TypeScript can depend on them.substringkeeps JavaScript's clamping exactly;sliceis 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].xis still the old value natively and9under Node, and[p, p]is two records natively and one object twice here. The reverse also holds: afterconst r = ps[0]; ps[0] = q,rreadsq'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 isundefineduntil written, soa[1] + 1.0is1natively andNaNhere. A slot of anish:simdvector array is the zero vector natively andundefinedhere, soextract(a[1], 0)is0natively andreplace(a[1], 0, x)throws here.--emit-tswrites each of these as a zero-fillednewArray, each vector slot its own zero typed array. -
The typed-array names are plain arrays natively, without
pushandpop.Float64Arrayisf64[]in the language, and under Node it is JavaScript's fixed-length typed array. A receiver spelled with the name refusespushandpopat compile time (NL2415), so theTypeError: t.push is not a functiona program could once reach here is a compile error natively too. A value the spelling does not reach — through another module'stypealias, out of aMaporSet, or a generic'sTresult — still pushes natively and throws here (LANGUAGE.md). -
A ranged integer is unchecked.
integer<Lo, Hi>is an alias ofnumberinruntime/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-tswrites it as an earlyreturninstead. Every other part ofResultworks —Ok,Err,isOk,isErr,.value,.error,unwrapOr,expect. -
Number(s)keeps JavaScript's parsing.Numberis a constructor carrying statics (Number.isNaNamong them) that both Node and the prelude itself need, so it is left alone; it differs from Nish's on the0band0oprefixes. -
Arena.used()reports zero, because there is no arena. A program printing it is measuring the native allocator by definition. -
i64andu64are out, for the same reason i32 mode is.runtime/shim.mjsrepresents them as BigInt — the only JavaScript type that holds 64 bits and wraps where the native ones wrap — and unrewritten source writesn + 1, which JavaScript refuses to mix with a BigInt. SotoI64,toU64andf64ToBitsthrow aTypeErrorat 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'sregisterHooks, which Bun does not have (Export named 'registerHooks' not found), andruntime/node.mjs, the host the shim installs, importsnode:fs,node:child_processandnode:os, which a browser does not have.runtime/core.mjsimports 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)ands.spawn(() => ...)reach the samespawn, which sees that no slot was written (an omitted argument isundefined, neither below zero nor at or above it) and runs the task with nothing to store; an arrow task's captures are theconsts its closure reads, which cannot change.usingitself needs--js-explicit-resource-managementon Node 22 and is native from Node 24; Node 22's flaggedusingnever 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
f64sum) 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 firstspawnto the end of the block, where the two would differ. A store tog.valueitself reaches theMutex, because the guard is theMutex's own storage. -
A
Channelis an array queue under Node.sendpushes, andfor (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
spawnbefore 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.

