Node.js honors the age-old unix tradition of the shbang line. Therefore all you need to do to make your node.js script behave like a regular executable program is to add this as the first line:
#! /usr/bin/env node
Technically this does not run node but rather it runs the env
comand (available on all unixen) which then finds where node.js is installed and runs it. This allows your script to be portable accross multiple distros (ubuntu, redhat etc.) and accross different unixes (Linux, MacOS, BSD etc.).
Then you just need to make your script executable:
chmod +x your-script.js
On Windows however, it gets a bit more complicated. However, npm has built-in features to turn your script into a proper command so you don't even need to do:
./your-script.js
You can just do:
your-script
All you need to do is:
- Add the shbang line to your script.
- If on unix do the
chmod +x
thing.
- Turn your script into an npm project (if not already an npm project) by putting it into its own folder then running
npm init
inside that folder (this will create a package.json file)
Edit your package.json file and add a bin
property
"bin" : {
"your-script" : "./your-script.js"
}
Run npm link
in the directory