I have a web server written in Node.js and I would like to launch with a specific folder. I'm not sure how to access arguments in JavaScript. I'm running node like this:
$ node server.js folder
here server.js
is my server code. Node.js help says this is possible:
$ node -h
Usage: node [options] script.js [arguments]
How would I access those arguments in JavaScript? Somehow I was not able to find this information on the web.
If you want to run something like this :
--
Or something like :
--
The up-to-date right answer for this it to use the minimist library. We used to use node-optimist but it has since been deprecated.
Here is an example of how to use it taken straight from the minimist documentation:
-
-
To normalize the arguments like a regular javascript function would receive, I do this in my node.js shell scripts:
Note that the first arg is usually the path to nodejs, and the second arg is the location of the script you're executing.
Several great answers here, but it all seems very complex. This is very similar to how bash scripts access argument values and it's already provided standard with node.js as MooGoo pointed out. (Just to make it understandable to somebody that's new to node.js)
Example:
Most of the people have given good answers. I would also like to contribute something here. I am providing the answer using
lodash
library to iterate through all command line arguments we pass while starting the app:To run above code just run following commands:
The result will be:
Although Above answers are perfect, and someone has already suggested yargs, using the package is really easy. This is a nice package which makes passing arguments to command line really easy.
Please visit https://yargs.js.org/ for more info.