snippetjavascriptCritical
How do I pass command line arguments to a Node.js program and receive them?
Viewed 0 times
programhowlineandthemnodecommandreceivepassarguments
Problem
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:
here
How would I access those arguments in JavaScript? Somehow I was not able to find this information on the web.
$ node server.js folderhere
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.
Solution
Standard Method (no library)
The arguments are stored in
Here are the node docs on handling command line args:
This will generate:
The arguments are stored in
process.argvHere are the node docs on handling command line args:
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.// print process.argv
process.argv.forEach(function (val, index, array) {
console.log(index + ': ' + val);
});
This will generate:
$ node process-2.js one two=three four
0: node
1: /Users/mjr/work/node/process-2.js
2: one
3: two=three
4: four
Context
Stack Overflow Q#4351521, score: 3774
Revisions (0)
No revisions yet.