DEV Community

Cover image for Your Script's Shape Decides Which Exit Code You Get
Mustafa ERBAY
Mustafa ERBAY

Posted on Originally published at mustafaerbay.com.tr

Your Script's Shape Decides Which Exit Code You Get

Since Node 22 you can run the scripts in your package.json without going
through npm at all: node --run build. The pitch is one word — speed. Node's own
documentation does not hide it: the implementation is "intentionally more
limited, in order to focus on top performance for the most common use cases".

Two of those limitations are spelled out in the docs. Two differences that turned
up in today's measurements are not in the docs at all, and the second one is the
surprise: under node --run, the shape of your script decides which exit code
the same death gets.
A script that kills itself with SIGKILL returns 0 when it
is a single command and 1 once a true && is put in front of it. Under npm run
that same death is 137 either way — three codes in total, two of them separated
by nothing but syntax.

The cause is a layer neither side documents: node --run hands the command to a
/bin/sh, and whether that shell survives decides the exit code. Every output
below comes from my own machine, verbatim.

Speed first, because that is why anyone switches

The lab is a clean package with a single noop script that does nothing. Each
command ran 21 times; the numbers are medians (Node v22.16.0, npm 10.9.2, Apple
Silicon):

npm run noop             n=21 median=   88.6 ms  p10=  87.2  p90= 101.1
node --run noop          n=21 median=   28.9 ms  p10=  28.4  p90=  32.6
node -e 0 (direct)       n=21 median=   18.1 ms  p10=  17.7  p90=  18.7
Enter fullscreen mode Exit fullscreen mode

That is 59.7 milliseconds per call. Most of it has to be npm's own startup cost —
node --run sits just 10.8 ms above a bare Node start — but the gap was never
broken down line by line here, so "most of it" is as far as the claim goes. In
isolation the saving is almost funny; it only starts to matter as the call count
grows. In a build pipeline, or in a command a watcher fires on every file change,
those 60 milliseconds get multiplied by the number of calls.

The saving is real. The question is what it is traded for.

Difference one: pre and post scripts never run

npm's rule is name-based: when you call the build script, npm also runs
prebuild and postbuild if scripts with those names exist. Its own docs put it
in one line: "Pre and post commands with matching names will be run for those
as well (e.g. …)".

All three scripts append a line to a file, so the same target under two runners
leaves two different traces:

$ npm run build
prebuild ran
build ran
postbuild ran

$ node --run build
build ran
Enter fullscreen mode Exit fullscreen mode

Node is not hiding this. It is the first bullet under "Intentional limitations":
"Running pre or post scripts in addition to the specified script." So this is
not a bug, it is a contract difference. The trouble is that the difference has no
symptom: node --run build exits zero, nothing turns red, and a job that should
have happened simply did not.

This is not theoretical for me. This blog's package.json holds 15 scripts, and
one of them is exactly that kind of gate:

"prebuild": "node scripts/migrate-content.mjs",
"build": "astro build && node scripts/copy-blog-assets.mjs && npx pagefind --site dist/client"
Enter fullscreen mode Exit fullscreen mode

migrate-content.mjs is the step that moves the posts' .mdx files into the
database that feeds the site. And the gate has been missed for real once: on
15 September one of my workflows called the build directly with npx astro
build
, so prebuild never ran, data/content.db was never produced, and page
rendering fell over with "directory does not exist". The fix commit is 3c58b06a
and its note reads: "npx astro build doğrudan çağrıldığı için npm prebuild
(migrate-content) ATLANIYORDU" — the trigger was bypassing npm, not node --run,
but it is the same gate.

Since that day the order is written out by hand in my pipeline: the workflow
calls migrate-content.mjs first and runs astro build second. So node --run
could not spring this trap on my pipeline today. The price of that is visible
too: migrate-content.mjs is now called by hand in six separate places — the
prebuild entry in package.json, four workflows and one deploy script. None of
them knows about the others.

The quiet part: the artifact gets built, and it is empty

Framed as "one line did not run", the difference above looks small. It does not
feel small in practice, because a pre script usually prepares the input of the
main script. The lab reproduces the shape of my own pipeline: generate.mjs
writes content into a JSON file, compile.mjs reads that file and produces
output — and when the file is missing it carries on with empty values instead of
crashing, the way most real compilers do.

$ npm run compile
content migrated: 1434 records
compile finished: records=1434
exit=0
out.txt: records=1434 stamp=2026-11-20T14:05:43.118Z (a second run of the same
lab as the Turkish article, with the script names in English)

$ node --run compile
compile finished: records=0
exit=0
out.txt: records=0 stamp=none
Enter fullscreen mode Exit fullscreen mode

Both runs ended with zero, both said the compile finished. One produced an
artifact with 1,434 records in it, the other an empty file. Nothing in the output
distinguishes them; the only way to see the difference is to look inside the
artifact.

How annoying a quietly successful call can be came up here before, in a
measurement of fsync returning success with durability switched
off
;
the culprit there was a kernel knob, the culprit here is the way my own script is
written. That is why the pre-script question is hard to wave away. In a build pipeline the
pre script usually does quiet preparation: generate a schema, stamp a version,
migrate a database. Drop that preparation and the product still comes out; it
just comes out hollow. In my case "hollow" means the post written that day never
appears on the site.

Naming a script preview is not an innocent choice

npm's pre-script rule looks at the first three letters of the name, not at your
intent. The lab has both a view and a preview script, each meaningful on its
own:

$ npm run view
preview ran
view ran

$ node --run view
view ran
Enter fullscreen mode Exit fullscreen mode

npm read preview not as a page preview but as the pre script of view. My own
package has a preview too (astro preview), and the only reason nothing has
ever gone wrong is that there is no script named view. The day someone adds
one, a dev server will quietly come up on every npm run view. node --run
never applies the rule — and for the same reason it never honours the pre scripts
you set up on purpose.

Difference two: your exit code collapses to 1

Here is where the documentation goes quiet. One script exits with 42, another
with 7:

npm run fail    exit=42        node --run fail    exit=1
npm run fail2   exit=7         node --run fail2   exit=1
Enter fullscreen mode Exit fullscreen mode

npm carries the script's code through; node --run flattens everything to 1,
three runs out of three. The behaviour comes from ProcessRunner::OnExit in
src/node_task_runner.cc (the block below is from main; the logic is identical
in the versions timed here, only the underscore in the variable name moves between
branches):

void ProcessRunner::OnExit(int64_t exit_status, int term_signal) {
  if (exit_status > 0) {
    init_result_->exit_code_ = ExitCode::kGenericUserError;
  } else {
    init_result_->exit_code_ = ExitCode::kNoFailure;
  }
}
Enter fullscreen mode Exit fullscreen mode

Every code above zero becomes one "generic user error", which is 1. Most of the
time that costs nothing: a shell under set -e and a CI step both only ask "zero
or not". But if something reads the code itself — a wrapper that says "77 means
we hit the quota, retry" or a Makefile branching on status — that logic does not
work under node --run. And it will not say so; it still sees a failure, just the
wrong one.

Difference three: one death, two codes by script shape

Look at that function again: it takes a term_signal parameter and never uses
it. When a child process dies from a signal, libuv reports exit_status as 0 and
puts the signal number into term_signal. A function that only looks at the first
value falls into the else branch, and the result is "success".

The first measurement confirmed exactly that. A single-command script that kills
itself:

npm run sigkill   exit=137      node --run sigkill   exit=0
npm run sigterm   exit=143      node --run sigterm   exit=0
Enter fullscreen mode Exit fullscreen mode

137 = 128 + 9, that is SIGKILL: the standard signature of a build that blew past
a container memory limit. npm run tells you. node --run says zero.

Then a harmless true && went in front of the same command, and the answer
changed:

script                                         node --run   npm run
sigkill  (single command)                               0       137
true && sigkill  (chain)                                1       137
sigkill && echo second  (chain)                         1       137
sigkill | cat  (pipe, first stage dies)                 0         0
echo hi | sigkill  (pipe, last stage dies)              1       137
Enter fullscreen mode Exit fullscreen mode

A single && turns the exit code from 0 into 1. The two pipe rows say something
else, and here npm run does not save you either: a shell takes a pipeline's exit
code from its last stage, so if the process that dies is not the last one,
both runners return zero. In that case the signal is not lost somewhere specific
to node --run; it is lost in the shell's own rule.

The reason for the difference in the chain shows up in the process tree — here is
node --run's child, caught while running:

$ node --run u_tek            # pid 17383
17385 17383 node -e setTimeout(()=>0,8000)

$ node --run u_zincir         # pid 17399
17401 17399 /bin/sh -c true && node -e "setTimeout(()=>0,8000)"
17402 17401 node -e setTimeout(()=>0,8000)
Enter fullscreen mode Exit fullscreen mode

node --run always hands the command to /bin/sh -c — the shell's name is a
constant in src/node_task_runner.h: /bin/sh on POSIX, cmd.exe on Windows. For one simple command the
shell execs itself away, so the process that dies is the direct child of
--run and the term_signal path applies: 0. In a chain the shell stays in the
middle; when the grandchild dies from a signal the shell exits normally with
137, and the if above reads that as an ordinary code and flattens it to 1.

Which process dies matters just as much. With the same chained script, changing
the target changes the answer:

chained script, killed the shell (the direct child)   -> node --run exit=0
chained script, killed the inner node process         -> node --run exit=1
Enter fullscreen mode Exit fullscreen mode

The rule in one sentence: if node --run's direct child dies from a signal, the
result is zero.
Whether that child is your script or an interposed shell is
decided by whether your script is a single command or a chain. The irony is that
the shell is what protects you here: the only layer that reported the failure at
all was that sh I did not know was there.

Both halves happen in practice. If the OOM killer takes a single process inside a
chained script, you get 1 — the wrong code, but still a failure. If a signal goes
to the whole process group, as when a CI job is cancelled, the shell dies too, the
direct child is gone by signal, and the code drops to zero.

Diagram

This is a known problem, still open

The interposed shell has an open entry in Node's tracker: #65712, filed on
1 September 2026, still open. The title says it outright — "node --run should
find a way to avoid keeping a shell around and properly forward signals" — and
the body describes node --run running as PID 1 in Docker, where the shell can
swallow signals and linger.

Two open pull requests point at the same place: #63978 removes the subshell
entirely (run node --run scripts without a subshell), and #63991 adds a flag
to bring pre scripts back. Both have been open since June 2026. So neither of
the two contract differences in this article is a frozen rule; they may change.
That is why every table here carries its version label.

Environment variables and PATH

npm leaves a pile of variables behind for the script. The lab package above shows
19 of them starting with npm_ (npm_package_json, npm_execpath,
npm_lifecycle_event, the npm_config_* family). That count moves with the
package's own fields and the local npm configuration, so 19 is this lab's number,
not a constant. node --run leaves two: NODE_RUN_SCRIPT_NAME and
NODE_RUN_PACKAGE_JSON_PATH. Both are documented, both arrived in Node 22.3.

The practical consequence: a script that prints a version by reading
npm_package_version finds that variable empty under node --run and either
crashes or writes undefined. A grep across my own repository finds not a single
line reading those variables — the first zero in a while that made me happy.

One more fine print item in the docs: variables loaded with --env-file are not
applied to the command --run executes. Handing Node a .env file and assuming
the script will see it is wrong.

The PATH side came out better than expected. Both runners found a binary placed
in node_modules/.bin, and the documentation goes further: --run prepends
node_modules/.bin for every ancestor directory that has one.

Where a migration snags

Passing arguments needs --. It is mandatory in both, and both carry
everything after it the same way:

$ npm run argecho -- --verbose
argv: ["--verbose"]

$ node --run argecho -- --verbose
argv: ["--verbose"]
Enter fullscreen mode Exit fullscreen mode

Forget the -- and the paths diverge, with both getting it wrong in different
ways: npm swallows --verbose as its own flag, while node --run takes it for a
Node flag and dies with node: bad option: --verbose.

A missing script and a bare call are different things. Ask for a script that
does not exist and node --run prints Missing script, lists the available
scripts and exits 1 — that much is there in both versions on this machine. Call
--run with no command at all and it answers --run requires an argument and
exits 9, Node's "invalid command line argument" code. The documented
behaviour where a bare call lists the scripts arrived in 24.22 and 26.9; neither
version here has it yet.

Calling from a subdirectory works the same in both. node --run walks up to
find package.json and runs the command in that file's directory; npm does the
same. Called from two levels deep, both set cwd to the package root. The
difference I went looking for is not there.

Scan your own scripts before you switch

The migration is cheap, but the order matters. These are the five questions worth
asking first:

  1. Any pre/post scripts? List the script names, prefix each with pre/post and compare against the list. The reverse holds too: if a script starting with pre has the rest of its name matching another script (preview → view), there is a hidden link there.
  2. Does anything read the exit code? Wrappers, Makefile branches, if blocks in CI. Places that only ask "is it zero" are safe.
  3. Can any step die from a signal? A build with a memory limit, a test under a timeout. If the script is a single command the code drops to zero; if it is a chain it becomes 1. Either way the real code is lost.
  4. Does any script read an npm_ variable? grep -rn 'npm_package\|npm_config\|npm_lifecycle' answers that in a second.
  5. Do you lean on npm-specific flags like --if-present, workspaces or npm exec? --run has no equivalent; an optional step built on --if-present stops at the first missing script after the switch.

You can also close the signal hole without migrating at all: call the critical
step directly (node scripts/build.mjs), or run the CI step from a shell and
carry the code yourself. A shell reports a signal as 128 + number; every intermediate layer
that does not read that number drops it.

One boundary note: all of this was timed on macOS, with POSIX signals. On Windows
node --run goes down a different path, through cmd.exe, and there are no POSIX
signals there; that behaviour was not timed here, so do not carry these
conclusions over to Windows.

Measure it yourself in ten minutes

The whole table above is reproducible in a single folder, and running it on your
own version beats taking these numbers, because upstream is trying to change both
behaviours. An empty directory and this package.json are enough:

{
  "name": "run-lab",
  "private": true,
  "scripts": {
    "prebuild": "node -e \"require('fs').appendFileSync('trace.log','prebuild\\n')\"",
    "build": "node -e \"require('fs').appendFileSync('trace.log','build\\n')\"",
    "fail": "node -e \"process.exit(42)\"",
    "sigkill": "node -e \"process.kill(process.pid,'SIGKILL')\"",
    "sigkillchain": "true && node -e \"process.kill(process.pid,'SIGKILL')\""
  }
}
Enter fullscreen mode Exit fullscreen mode

Then, in order:

rm -f trace.log && npm run build  && cat trace.log   # two lines: prebuild, build
rm -f trace.log && node --run build && cat trace.log  # one line: build
npm run fail        >/dev/null 2>&1; echo "npm=$?"   # 42
node --run fail     >/dev/null 2>&1; echo "run=$?"   # 1
npm run sigkill        >/dev/null 2>&1; echo "npm=$?"   # 137
node --run sigkill     >/dev/null 2>&1; echo "run=$?"   # 0
node --run sigkillchain >/dev/null 2>&1; echo "run=$?"   # 1
Enter fullscreen mode Exit fullscreen mode

Two warnings. First: do not put the exit code behind a pipe. Write
node --run fail | tail -1 and $? belongs to the last element of the pipeline,
not to the script — that trap caught me on the first attempt; I saw a 0, was not
pleased, and got suspicious. Second: do not trust a single run when timing. The
numbers here are medians of 21 runs, and the first run is misleading on both sides
because the file cache is cold.

To see the process tree yourself, start a long-running script and look at
node --run's child with ps -ax -o pid=,ppid=,command=: a single command shows
your script, a chain shows /bin/sh -c.

What I will do

My pipeline is staying on npm run, but not because the tool lies. npm run is
no saint either: on a piped script it loses the signal completely and returns
zero. What stops me is this: under node --run the shape of my script decides how failure gets
reported. Adding or removing a single && — the most ordinary edit I make while
tuning a build — moves the code for the same death between 0 and 1. I would rather
not have the failure contract depend on a piece of syntax that has nothing to do
with the logic.

That is not the only defensible answer. In a project with one-line scripts, no pre
scripts and nothing reading exit codes, node --run is a free speed-up. And
upstream has both questions open; if the shell goes away, the table gets rewritten.

The lesson going into my own notes today: when two tools look like they do the
same job, look at how each one reports failure — and ask that question not
only of the tool but of the input you hand it. Nothing about the tool changed in
this measurement; two characters were added to a script and the answer changed.

Official Sources

Top comments (0)