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:
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.
npm i yargs
const yargs = require("yargs");
const argv = yargs.argv;
console.log(argv);
Please visit https://yargs.js.org/ for more info.
If your script is called myScript.js and you want to pass the first and last name, 'Sean Worthington', as arguments like below:
node myScript.js Sean Worthington
Then within your script you write:
var firstName = process.argv[2]; // Will be set to 'Sean'
var lastName = process.argv[3]; // Will be set to 'Worthington'
Parsing argument based on standard input ( --key=value
)
const argv = (() => {
const arguments = {};
process.argv.slice(2).map( (element) => {
const matches = element.match( '--([a-zA-Z0-9]+)=(.*)');
if ( matches ){
arguments[matches[1]] = matches[2]
.replace(/^['"]/, '').replace(/['"]$/, '');
}
});
return arguments;
})();
Command example
node app.js --name=stackoverflow --id=10 another-argument --text="Hello World"
Result of argv: console.log(argv)
{
name: "stackoverflow",
id: "10",
text: "Hello World"
}
as stated in the node docs The process.argv property returns an array containing the command line arguments passed when the Node.js process was launched.
For example, assuming the following script for process-args.js:
// print process.argv
process.argv.forEach((val, index) => {
console.log(`${index}: ${val}`);
});
Launching the Node.js process as:
$ node process-args.js one two=three four
Would generate the output:
0: /usr/local/bin/node
1: /Users/mjr/work/node/process-args.js
2: one
3: two=three
4: four
The simplest way of retrieving arguments in Node.js is via the process.argv array. This is a global object that you can use without importing any additional libraries to use it. You simply need to pass arguments to a Node.js application, just like we showed earlier, and these arguments can be accessed within the application via the process.argv array.
The first element of the process.argv array will always be a file system path pointing to the node executable. The second element is the name of the JavaScript file that is being executed. And the third element is the first argument that was actually passed by the user.
'use strict';
for (let j = 0; j < process.argv.length; j++) {
console.log(j + ' -> ' + (process.argv[j]));
}
All this script does is loop through the process.argv array and prints the indexes, along with the elements stored in those indexes. It's very useful for debugging if you ever question what arguments you're receiving, and in what order.
You can also use libraries like yargs for working with commnadline arguments.
The easiest way to parse command-line arguments in NodeJS is using the stdio module. Inspired by UNIX getopt
utility, it is as trivial as follows:
var stdio = require('stdio');
var ops = stdio.getopt({
'check': {key: 'c', args: 2, description: 'What this option means'},
'map': {key: 'm', description: 'Another description'},
'kaka': {args: 1, required: true},
'ooo': {key: 'o'}
});
If you run the previous code with this command:
node <your_script.js> -c 23 45 --map -k 23 file1 file2
Then ops
object will be as follows:
{ check: [ '23', '45' ],
args: [ 'file1', 'file2' ],
map: true,
kaka: '23' }
So you can use it as you want. For instance:
if (ops.kaka && ops.check) {
console.log(ops.kaka + ops.check[0]);
}
Grouped options are also supported, so you can write -om
instead of -o -m
.
Furthermore, stdio
can generate a help/usage output automatically. If you call ops.printHelp()
you'll get the following:
USAGE: node something.js [--check <ARG1> <ARG2>] [--kaka] [--ooo] [--map]
-c, --check <ARG1> <ARG2> What this option means (mandatory)
-k, --kaka (mandatory)
--map Another description
-o, --ooo
The previous message is shown also if a mandatory option is not given (preceded by the error message) or if it is mispecified (for instance, if you specify a single arg for an option and it needs 2).
You can install stdio module using NPM:
npm install stdio