• Node.js Video Tutorials

Node.js - Command Line Options



Any JavaScript file (with .js extension) can be executed from the command prompt, using it as a command line option to the node executable.

PS D:\nodejs> node hello.js

You can invoke the Node.js REPL by running node without any option.

PS D:\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

PS D:\nodejs> node --help

Some of the frequently used command line options (sometimes also called switches) are as follows −

Display version

PS D:\nodejs> node -v
v20.9.0
PS D:\nodejs> node --version
v20.9.0

Evaluate script

PS D:\nodejs> node --eval "console.log(123)"
123
PS D:\nodejs> node -e "console.log(123)"
123

Show help

PS D:\nodejs> node -h
PS D:\nodejs> node –help

Start REPL

PS D:\nodejs> node -i
PS D:\nodejs> node –interactive

Load module

PS D:\nodejs> node -r "http"
PS D:\nodejs> node –require "http"

You can pass arguments to the script to be executed from the command line. The arguments are stored in a an array process.argv. The 0th element in the array is the nide executable, first element is the javascript file, followed by the arguments passed.

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

PS D:\nodejs> node hello.js TutorialsPoint
[ 'C:\\nodejs\\node.exe', 'D:\\nodejs\\a.js', 'TutorialsPoint' ]
Hello, TutorialsPoint

You can also accept input from the command line in Node.js. Node.js since version 7 provides the readline module for this purpose. The createInterface() method helps in setting input from a readable stream such as the process.stdin stream, which during the execution of a Node.js program is the terminal input, one line at a time.

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.

PS D:\nodejs> node a.js
What's your name?TutorialsPoint
Hi TutorialsPoint!

You can also set environment variables from the command line. Assign the values to one or more variables before the node executable name.

USER_ID=101 USER_NAME=admin node app.js

Inside the script, the environment variables are available as the properties of the process.env object.

process.env.USER_ID; // "101"
process.env.USER_NAME; // "admin"
Advertisements