Back to results for “npm & Packages”
Node.js › CLI Tools & Scripting with Node.js

What is a shebang line, and why does it need to be the first line of an executable Node.js CLI script?

Beginner

Answer

A shebang line (#!/usr/bin/env node) tells Unix-like operating systems which interpreter should execute the file when it's run directly as a program (like ./my-script.js) rather than being explicitly invoked via 'node my-script.js' -- using 'env node' rather than hardcoding a specific path like /usr/bin/node makes the script portable across systems where Node.js might be installed in different locations, since env looks up 'node' in the user's PATH.
#!/usr/bin/env node
console.log('Hello from a CLI tool!');

// After making it executable: chmod +x my-script.js
// It can then be run directly: ./my-script.js
Real-world example An npm package's CLI tool includes a shebang line in its entry file and is registered in package.json's 'bin' field, letting users run it directly as a command (like 'my-tool --help') after global installation, without needing to explicitly type 'node' before it.

Common follow-ups: How does the package.json 'bin' field work together with the shebang line to make an npm package installable as a global command?;Why doesn't the shebang line have any effect at all when the script is run on Windows?