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:
You can parse all arguments and check if they exist.
file: parse-cli-arguments.js:
module.exports = function(requiredArguments){
var arguments = {};
for (var index = 0; index < process.argv.length; index++) {
var re = new RegExp('--([A-Za-z0-9_]+)=([A/-Za-z0-9_]+)'),
matches = re.exec(process.argv[index]);
if(matches !== null) {
arguments[matches[1]] = matches[2];
}
}
for (var index = 0; index < requiredArguments.length; index++) {
if (arguments[requiredArguments[index]] === undefined) {
throw(requiredArguments[index] + ' not defined. Please add the argument with --' + requiredArguments[index]);
}
}
return arguments;
}
Than just do:
var arguments = require('./parse-cli-arguments')(['foo', 'bar', 'xpto']);
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:
// Lodash library
const _ = require('lodash');
// Function that goes through each CommandLine Arguments and prints it to the console.
const runApp = () => {
_.map(process.argv, (arg) => {
console.log(arg);
});
};
// Calling the function.
runApp();
To run above code just run following commands:
npm install
node index.js xyz abc 123 456
The result will be:
xyz
abc
123
456
npm install ps-grab
node greeting.js --user Abdennour --website http://abdennoor.com
--
var grab=require('ps-grab');
grab('--username') // return 'Abdennour'
grab('--action') // return 'http://abdennoor.com'
Or something like :
node vbox.js -OS redhat -VM template-12332 ;
--
var grab=require('ps-grab');
grab('-OS') // return 'redhat'
grab('-VM') // return 'template-12332'
command-line-args is worth a look!
You can set options using the main notation standards (learn more). These commands are all equivalent, setting the same values:
$ example --verbose --timeout=1000 --src one.js --src two.js
$ example --verbose --timeout 1000 --src one.js two.js
$ example -vt 1000 --src one.js two.js
$ example -vt 1000 one.js two.js
To access the values, first create a list of option definitions describing the options your application accepts. The type property is a setter function (the value supplied is passed through this), giving you full control over the value received.
const optionDefinitions = [
{ name: 'verbose', alias: 'v', type: Boolean },
{ name: 'src', type: String, multiple: true, defaultOption: true },
{ name: 'timeout', alias: 't', type: Number }
]
Next, parse the options using commandLineArgs():
const commandLineArgs = require('command-line-args')
const options = commandLineArgs(optionDefinitions)
options
now looks like this:
{
src: [
'one.js',
'two.js'
],
verbose: true,
timeout: 1000
}
Beside the above typical usage, you can configure command-line-args to accept more advanced syntax forms.
Command-based syntax (git style) in the form:
$ executable <command> [options]
For example.
$ git commit --squash -m "This is my commit message"
Command and sub-command syntax (docker style) in the form:
$ executable <command> [options] <sub-command> [options]
For example.
$ docker run --detached --image centos bash -c yum install -y httpd
A usage guide (typically printed when --help
is set) can be generated using command-line-usage. See the examples below and read the documentation for instructions how to create them.
A typical usage guide example.
The polymer-cli usage guide is a good real-life example.
There is plenty more to learn, please see the wiki for examples and documentation.
If you want to do this in vanilla JS/ES6 you can use the following solution
worked only in NodeJS > 6
const args = process.argv
.slice(2)
.map((val, i)=>{
let object = {};
let [regexForProp, regexForVal] = (() => [new RegExp('^(.+?)='), new RegExp('\=(.*)')] )();
let [prop, value] = (() => [regexForProp.exec(val), regexForVal.exec(val)] )();
if(!prop){
object[val] = true;
return object;
} else {
object[prop[1]] = value[1] ;
return object
}
})
.reduce((obj, item) => {
let prop = Object.keys(item)[0];
obj[prop] = item[prop];
return obj;
}, {});
And this command
node index.js host=http://google.com port=8080 production
will produce the following result
console.log(args);//{ host:'http://google.com',port:'8080',production:true }
console.log(args.host);//http://google.com
console.log(args.port);//8080
console.log(args.production);//true
p.s. Please correct the code in map and reduce function if you find more elegant solution, thanks ;)
proj.js
for(var i=0;i<process.argv.length;i++){
console.log(process.argv[i]);
}
Terminal:
nodemon app.js "arg1" "arg2" "arg3"
Result:
0 'C:\\Program Files\\nodejs\\node.exe'
1 'C:\\Users\\Nouman\\Desktop\\Node\\camer nodejs\\proj.js'
2 'arg1' your first argument you passed.
3 'arg2' your second argument you passed.
4 'arg3' your third argument you passed.
Explaination:
0
: The directory of node.exe in your maching (C:\Program Files\nodejs\node.exe')
1
: The directory of your project file. (proj.js)
2
: Your first argument to node (arg1)
3
: Your second argument to node (arg2)
4
: Your third argument to node (arg3)
your actual arguments start form 2nd
index of argv
array, that is process.argv[2]
.