
How to get arguments when executing from the command line in javascript (nodejs), with sample code. I'm recording this as a reminder.
This is useful, for example, when running javascript as a batch program using npm run. No external libraries are used, so you can just copy and paste the code.
Software | Version |
---|---|
node.js | v16.13.0 |
You can pass arguments from shell or command-line like this.
This is the same as the normal way of passing arguments from shell (Windows command line passing to batch).
> node sample1.js arg1test arg2test samplearg3
Now you can pass the three arguments "arg1test", "arg2test", and "samplearg3" to the "sample1.js" javascript .
To pass a string containing spaces as a single argument, enclose it in double quotation marks as shown below.
> node sample1.js "arg1-1 arg1-2" "arg2-1 arg2-2"
Now we can pass the two strings "arg1-1 arg1-2" and "arg2-1 arg2-2" as arguments to sample1.js at runtime, respectively.
Let's prepare the following sample.js.
console.log(process.argv);
OK. Let's pass three arguments to this script.
> node sample.js "arg1-1 arg1-2" arg2 arg3
[
'C:\\Program Files2\nodejs\\node.exe',
'C:\\02_data\01_dev\03_nodachisoftweb\\nodachisoft_www\\\batch\ sample.js',
'arg1-1 arg1-2',
'arg2',
'arg3'.
]
You can refer to the arguments passed from the command line in process.argv.
The contents of process.argv are as follows
Subscript (number) | Contents |
---|---|
[0] | full path of nodejs |
[1] | Full path of the executed javascript file |
[2] and onwards | String passed as command argument |
Specifically, the array of arguments passed to sample.js can be obtained as follows.
var argsStr = process.argv.slice(2);
var count = 0;
argsStr.forEach(arg=>{console.log(`arg[${count++}]=${arg}`)});
Try to run it with passing 3 arguments.
> node sample.js "arg1-1 arg1-2" arg2 "arg3-1 arg3-2"
arg[0]=arg1-1 arg1-2
arg[1]=arg2
arg[2]=arg3-1 arg3-2
We can now check the contents of each of the purely passed arguments.
date | modification |
---|---|
none |
Thank you for your message.
Sorry. The Error has occurred.We apologize for the inconvenience.Please try again in a few minutes or contact us via DM below.
Twitter:@NodachiSoft_engName:Send the following information to us. If you are happy with your submission, please click "Send". If you want to modify it, please click "Back".
Name: