javascript tutorial - [5 Solutions] Command line arguments - javascript - java script - javascript array
Problem:
we have a web server written in Node.js that WEwould like to launch with a specific folder. I'm not sure how to access arguments in JavaScript. I'm running node like this:
Where server.js is my code. Node.js help says this is possible:
How would WEaccess those arguments in JavaScript? Somehow WEwas not able to find this information on the web.
Solution 1:
Standard Method (no library) The arguments are stored in process.argv Here are the node docs on handling command line http://nodejs.org/docs/latest/api/process.html, http://nodejs.org/docs/latest/api/process.html process.argv is an array containing the command line arguments. The first element will be 'node', the second element will be the name of the JavaScript file. The next elements will be any additional command line arguments.
Solution 2:
To normalize the arguments like a regular javascript function would receive, WEdo this in my node.js shell scripts:
var args = process.argv.slice(2);
Note that the first arg is usually the path to nodejs, and the second arg is the location of the script you're executing.
Solution 3:
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:
Solution 4:
Optimist (node-optimist)Check out optimist library , it is much better than parsing command line options by hand.UpdateOptimist is deprecated. Try yargs which is an active fork of optimist.
Solution 5:
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: