Skip to content

Hashbang comments: executable JavaScript files (ES2023)

  • What a hashbang line does for the operating system and what it means to the JavaScript engine.
  • The exact rule for where #! is allowed.
  • How to write a runnable Node.js CLI script, including passing flags with env -S.
  • The CRLF, BOM and Windows pitfalls that break executable scripts.

TL;DR: a JavaScript file may start with a line beginning #!, such as #!/usr/bin/env node. On Unix-like systems the kernel reads that line to pick the interpreter when you run the file directly (./tool.mjs). The JavaScript engine treats it as a single-line comment and ignores it. It is valid only as the very first characters of a script or module.

Server runtimes such as Node.js always skipped this line. ECMAScript 2023 made it part of the language grammar, so browsers and other engines accept it too.

Command-line tools written in JavaScript need a first line that tells the shell which program runs them. Before ES2023, #! was not valid JavaScript: Node.js stripped the line before parsing, but other engines and tools that parse files directly saw a syntax error and had to special-case it. The standard “hashbang grammar” lets every conforming parser accept the same file.

Running the samples: save the sample as an .mjs file, mark it executable and run it on Linux or macOS with Node.js 22 on your PATH. The outputs shown were produced with Node.js 22.23 on Linux.

#!/usr/bin/env node
// OrdersPortal CLI: print a one-line summary for the order totals passed as arguments.
const totals = process.argv.slice(2).map(Number);
if (totals.length === 0 || totals.some(Number.isNaN)) {
console.error('usage: orders-report <total> [total ...]');
process.exit(2);
}
const sum = totals.reduce((a, b) => a + b, 0);
console.log(`${totals.length} orders, total ${sum.toFixed(2)}, average ${(sum / totals.length).toFixed(2)}`);
Terminal window
chmod +x orders-report.mjs
./orders-report.mjs 40 15.5 120
./orders-report.mjs; echo "exit $?"
node orders-report.mjs 10 20

Output:

3 orders, total 175.50, average 58.50
usage: orders-report <total> [total ...]
exit 2
2 orders, total 30.00, average 15.00

Running it with ./ uses the hashbang; running it with node file.mjs ignores it. Both work from the same file.

  • Grammar: HashbangComment :: #! SingleLineCommentChars?. Everything from #! to the end of the line is a comment.
  • Position: the lexer looks for it only at the start of a Script or Module. Not even a space, a blank line or another comment may come before it.
  • Where it counts as a start: any source parsed as a whole script or module, so files, <script> elements, eval() code and Node.js vm.Script all accept it. A Function constructor body is not a script, so it does not.
  • Only one meaning to the engine: it is discarded like any comment. It does not choose the module type; that still comes from the file extension, package.json "type" or the <script type="module"> attribute.
console.log(eval('#!ignored\n1 + 1'));
try {
new Function('#!x\nreturn 1');
} catch (e) {
console.log('Function body:', e.constructor.name, e.message);
}

Output (the error message is V8’s wording):

2
Function body: SyntaxError Invalid or unexpected token

A file that starts with #!/usr/bin/env node (leading space) or has the hashbang on line 2 fails with SyntaxError: Invalid or unexpected token in Node.js 22.

The kernel checks the first two bytes of an executable file for #! and runs the named interpreter with the script path as an argument. #!/usr/bin/env node asks env to find node on the PATH, which works across version managers and installation paths, unlike a hard-coded #!/usr/local/bin/node.

Linux passes everything after the interpreter path as one argument, so #!/usr/bin/env node --no-warnings makes env look for a program literally named node --no-warnings. Use env -S (GNU coreutils 8.30 and later, macOS and FreeBSD) to split the string:

# Fragment: first line of a script that needs a Node.js flag
#!/usr/bin/env -S node --no-warnings

OrdersPortal publishes its report tool as an npm package. The bin field maps a command name to the script; npm links it into node_modules/.bin (or a global bin folder) when the package is installed.

{
"name": "orders-report",
"version": "1.0.0",
"type": "module",
"bin": { "orders-report": "./bin/orders-report.js" }
}

bin/orders-report.js starts with #!/usr/bin/env node, exactly like the sample above. npm’s documentation requires that line: without it the file is not started with node. On Windows, which ignores hashbangs, npm generates .cmd and PowerShell wrappers for each bin entry, so the same package works there too. Git stores the executable bit, so commit the file after chmod +x (or git update-index --chmod=+x) for clones on Unix.

  • Anything before #!. A blank line, a space, a license comment or a "use strict" above it makes the file a syntax error. Put the license comment on line 2.
  • Windows line endings. With CRLF, the kernel looks for an interpreter named node\r and fails with /usr/bin/env: 'node\r': No such file or directory, even though node file.mjs works. Save CLI scripts with LF endings and enforce it in .gitattributes.
  • A UTF-8 byte order mark. Node.js strips a BOM before parsing, but the kernel then sees three bytes before #! and does not treat the file as a script. Save without a BOM.
  • Passing flags without -S. #!/usr/bin/env node --flag fails on Linux. Use env -S, or set options in code or through NODE_OPTIONS.
  • Forgetting the executable bit. Without chmod +x, ./tool.mjs reports Permission denied.

According to MDN’s compatibility data, hashbang comments are accepted by Chrome 74, Edge 79, Firefox 67, Safari 13.1 (iOS 13.4), Node.js 0.10 (Node.js has always skipped the line), Deno 1.0 and Bun 1.0. Internet Explorer never supported it. TypeScript keeps a leading hashbang in its emitted JavaScript.

1. Is #!/usr/bin/env node JavaScript? Since ES2023, yes: it is a HashbangComment, a comment the engine ignores. It is valid only as the first characters of a script or module. Before ES2023 it was a host extension that Node.js handled by stripping the line.

2. Why /usr/bin/env node instead of the path to node? env searches the PATH, so the script runs with whichever Node.js the user has active, whether it came from a package manager, a version manager or a container image. A hard-coded path breaks on any machine where Node.js lives elsewhere.

3. Senior scenario: a CLI works with node bin/tool.js in CI but fails as npx tool for some Linux users with “No such file or directory”. What do you check? Check the first bytes (head -c 32 bin/tool.js | od -c). The usual causes are CRLF endings (node\r), a BOM before #!, or flags after node without env -S. Also confirm that no build step inserted a banner above the hashbang and that the published file is executable. Prevent recurrences with LF endings in .gitattributes and a CI smoke test that runs the installed binary rather than node file.

  • A hashbang line lets Unix-like systems run a JavaScript file directly; the engine treats it as a comment.
  • ES2023 standardized it; it must be the very first characters of the file.
  • Prefer #!/usr/bin/env node, and env -S when you need flags.
  • Use LF line endings, no BOM and the executable bit; npm bin scripts need the hashbang.