- Process
- Process.argv
NodeJS allows us, among other things, to build CLIs (Command Line Interfaces).
For that we need a way to receive command line arguments, which in Node is done using the built-in
process object.process
NodeJS provides a special object called
process that represents the current running program.You can use it to inspect the environment, the current working directory, and even exit the program when needed.
For example:
console.log(process.platform)
This prints the operating system platform, like
win32, linux, or darwin (Mac).process.argv
When you run a NodeJS program from the terminal, you can pass extra words (arguments) after the script name. These are stored in
process.argv.For example, if you run this command:
node my_script.js alpha beta
You can print the arguments like this:
console.log(process.argv)
The output might look like this:
[ '/path/to/node', '/path/to/my_script.js', 'alpha', 'beta' ]
The first two items are always the Node path and your script path. Any additional words you passed to the script come after that.
The
process.argv array can be cut as any other array using the .slice() method, so to get just the arguments that were passed you can doconst args = process.argv.slice(2) console.log(args)
Having access to the arguments that the user is passing is fundamental to develop command-line applications.