How do I pass command line arguments to a Node.js program and receive them?
In Node.js, you can pass command line arguments to your script the same as you would for any other command line application. Simply type your arguments after the script path separated with a space as shown below:
node task.js foo bar
Then you can retrieve the arguments from the process.argv
array like this:
process.argv.forEach((val, index) => {
console.log(index + ': ' + val);
});
The first element (index 0) is always a path to your Node.js executable and the second element (index 1) is a path to your script. Additional elements are the ones you pass when executing the script. In the case of the example above. The process.argv
array would look something like this:
0: /path/to/node
1: /path/to/task.js
2: foo
3: bar
You can also use packages such as commander
, yargs
or minimist
to help you handle and parse command line arguments.
Remember, command line arguments are string so you need to convert them to other types when necessary.
-
Best Node.js Application Monitoring Tools in 2023
Node.js Applications Performance Management and Monitoring tools enable code-level observability, faster recovery, troubleshooting, and easier maintenance of Node.js applications.
Comparisons -
Monitoring Linux with Node Exporter
This guide will teach you how to install and configure Prometheus and Node Exporter for monitoring your Linux servers
Guides
Make your mark
Join the writer's program
Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.
Write for usBuild on top of Better Stack
Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.
community@betterstack.comor submit a pull request and help us build better products for everyone.
See the full list of amazing projects on github