What is the correct syntax for running a Node.js script with command-line arguments on Linux or Mac?
To run the script with no arguments, I would simply use the command node stuff.js
, but in this case, I'd like to run a script called stuff.js
with the arguments "blah", "hee", "woohoo!"
.
Arguments can be passed to the script when it is executed, by writing them as a space-delimited list following the script file name. Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth.
Command line arguments (also known as positional parameters) are the arguments specified at the command prompt with a command or script to be executed. The locations at the command prompt of the arguments as well as the location of the command, or the script itself, are stored in corresponding variables.
Instead, we use the special variable $@ , which means, 'All of the command-line arguments to the shell script'. We also should put $@ inside double-quotes to handle the case of arguments containing spaces ( "$@" is special syntax and is equivalent to "$1" "$2" …).
See http://nodejs.org/docs/latest/api/process.html#process_process_argv
In summary you'll run it like
node stuff.js blah hee "whoohoo!"
Then your arguments are available in process.argv
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With