By using it as a command line option to the node executable, any JavaScript file (with the.js extension) can be run from the command prompt.
PSD:\nodejs> node hello.js
You can invoke the Node.js REPL by running node without any option.
PSD:\nodejs> node >
In addition, there are many options that can be used in the node command line. To get the available command line options, use –help
PSD:\nodejs> node --help
Some of the frequently used command line options (sometimes also called switches) are as follows −
Display version
PSD:\nodejs> node -v v20.9.0PSD:\nodejs> node --version v20.9.0
Evaluate script
PSD:\nodejs> node --eval "console.log(123)"123PSD:\nodejs> node -e "console.log(123)"123
Show help
PSD:\nodejs> node -h PSD:\nodejs> node –help
Start REPL
PSD:\nodejs> node -i PSD:\nodejs> node –interactive
Load module
PSD:\nodejs> node -r "http"PSD:\nodejs> node –require "http"
The script can be run from the command line by passing arguments. The parameters are kept in the process.argv array. The JavaScript file is the first element in the array, followed by the arguments supplied, and the nide executable is the 0th element.
Save the following script as hello.js and run it from command line, pass a string argument to it from command line.
const args = process.argv; console.log(args);const name = args[2]; console.log("Hello,", name);
In the terminal, enter
PSD:\nodejs> node hello.js thefullstack
['C:\\nodejs\\node.exe','D:\\nodejs\\a.js','thefullstack']
Hello, thefullstack
In Node.js, you can also take commands from the command line. For this, Node.js from version 7 has the readline module. One line at a time, the createInterface() method assists in setting input from a readable stream, like the process.stdin stream, which serves as the terminal input when a Node.js program is running.
Save the following code as hello.js
const readline =require('readline').createInterface({input: process.stdin,output: process.stdout,}); readline.question(`What's your name?`,name=>{ console.log(`Hi ${name}!`); readline.close();});
The question() method shows the first parameter (a question) and waits for the user input. It calls the callback function once enter is pressed.
Run from command line. Node runtime waits for user input and then echoes the output on the console.
PSD:\nodejs> node a.js
What's your name?thefullstack
Hi thefullstack
Setting environment variables from the command line is another option. Before the node executable name, assign the values to one or more variables.
USER_NAME=admin node app.js USER_ID=101
The environment variables are accessible within the script as the process.env object’s properties.
process.env.USER_ID;// "101" process.env.USER_NAME;// "admin"
It might be helpful: