5 minutes read

The CLI is an interface for human-computer interaction that uses text input from the keyboard. This method is convenient for when it is impossible or difficult to implement a graphical menu. At first, it was the only way to control a computer. But now it works as a powerful tool for administrators and developers. You may have seen hackers use the CLI to do shady stuff in movies, but in reality, you can use the CLI when working with operating systems without a graphical interface.

What is Node CLI?

With Node.js CLI (Command Line Interface), command line programs accept you to run operating system functions.

// Move to '/home' directory and list contents in it:
$ cd /home && ls -l

Some of the programs (such as Node.js) have their own command line interface to execute built-in functions.

# Check the Node.js version
$ node -v

# OR
$ node --version

# Read Node.js CLI manual
$ man node

# List all CLI options
$ node --help

CLI allows you to run scripts from the console with specific flags and control command output. It helps you check your code for mistakes, quickly run code snippets, and debug. So, let's learn more about CLI.

Check your code syntax

For example, you have a script that calls script.js but you don't have access to IDE, or your code editor can't highlight syntax mistakes in your code. So you can run node -c script.js or node --check script.js.

Node.js CLI has three main sections:
  1. Command: node;
  2. Options (Flags): -v, -c, --print;
  3. Path to JS script: /home/user/script.js.

To execute the command for your script file, make sure that the path to the file is correct. You also can change the directory to execute the command for a particular file.

# For example, your file path is: /home/user/script.js

$ node -c /home/user/script.js

# Or move to /home/user directory and run the command

$ cd /home/user
$ node script.js

Let's check this code:

// script.js

const definition = Husky is a;
const animals = ['dog', 'cat'];

console.log(definition + animals[0]);

Running script.js using CLI, you get:

$ node -c script.js

# It returns:

/script.js:1

const definition = Husky is a;

                         ^^
SyntaxError: Unexpected identifier
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1032:15)
    at checkSyntax (node:internal/main/check_syntax:66:3)
    at node:internal/main/check_syntax:39:3

As you can see, there is a problem with defining the variable — definition.

Let's resolve this problem, and check the code syntax again:

// script.js

const definition = 'Husky is a'; // use quotes to turn into string
const animals = ['dog', 'cat'];

console.log(definition + animals[0]);
$ node -c script.js

# If the syntax is OK, it won't return anything.

It comes in handy if you don't want to execute a full script and just want to be sure that the syntax is OK.

Run JavaScript code from the command line

There are two options to execute JS code from the command line: -p (or) --print or -e (or) --eval. They're the same, except --eval just executes JavaScript, but --print executes and gives an output too.

Here is how the --eval command works:

$ node -e '10+23'
# Returns: nothing

$ node -e 'console.log(10+23)'
# Returns: 33

$ node -e '[x, y] = ["lazy", "fox"]; console.log(x, y);'
# Returns: lazy fox

And this snippet uses -p to print and shows the corresponding output:

$ node -p '[x, y] = [32, 12]; x+y' # 44
$ node -p '"Hello World"' # 'Hello World'
$ node -p '150%4' # 2
$ node -p 66+44 # 110

As you can see, the -p option returns the result of your definition, just like REPL.

REPL is a read-eval-print loop, a simple programming environment.

Also, you can run node without any flags. It allows you to run Node,js in REPL mode. So, you can interactively write JavaScript expressions and have them evaluated immediately. Take a look at this code below:

$ node

Welcome to Node.js v16.17.1.
Type ".help" for more information.
> [x, y, z] = [12, 27, 99];
[ 12, 27, 99 ]

> x*y*z
32076

Also, REPL has editor mode. To enable it, type the .editor command inside Node CLI. When .editor is enabled, you can code just like in a simple code editor. To execute your code, press Control + D.

$ node

Welcome to Node.js v16.17.1.
Type ".help" for more information.
> .editor
// Entering editor mode (Ctrl+D to finish, Ctrl+C to cancel)
sentence = "The little brown pony";

function makeSlug(string) {
  return string.replaceAll(' ', '-').toLowerCase();
}

makeSlug(sentence);

# then press "Control + D"
# Here is the command output:
'The-little-brown-pony'

Note that CLI has built-in modules, functions, and classes. Enter the Node REPL and press the tab key twice, you'll see all the modules you can use.

Combine options

There is an easy and quick method to get an HTTP response from an API server and write it to a file.

You need to combine --experimental-fetch and --eval options to get server response.

By default, the fetch() method won't be defined when using Node.js LTS (16) version. So you need to set the experimental flag to use them. If you use Node.js (18) and later, the fetch() experimental feature is already activated. You don't need to set the --experimental-fetch flag to use the fetch() method.
$ node --experimental-fetch -e "fetch('https://jsonplaceholder.typicode.com/posts/1').then((res) => res.json()).then((data) => console.log(data))" > response.json

$ cat response.json

Here is the command output:

{
  userId: 1,
  id: 1,
  title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
  body: 'quia et suscipit\n' +
    'suscipit recusandae consequuntur expedita et cum\n' +
    'reprehenderit molestiae ut ut quas totam\n' +
    'nostrum rerum est autem sunt rem eveniet architecto'
}

The --eval option is useful when you only need the data output in console.log(). When using the -p option, all data is returned, like the first res.json() it will be Promise { <pending> }.

Conclusion

CLI can be a useful tool when you're working on projects. You can view all the CLI options in the official Node.js documentation. In common cases, CLI is a convenient tool for short code snippets when resolving math problems, parsing JSON data, and other tasks. Don't forget about the --check flag that allows you to check the syntax of JavaScript files, whenever you're coding small code snippets, notes, or building a complex app. Also, use the man node, which will help you remember the entire scope of the Node.js CLI with all the available commands.

7 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo