Shell scripting with Node.js
You can buy the offline version of this book (HTML, PDF, EPUB, MOBI) and support the free online version.
(Ad, please don’t block.)

3 Getting started with Node.js

This chapter explains the first steps with Node.js.

3.1 Getting help for Node.js

3.2 Installing Node.js and npm

The installer for Node.js also installs the package manager npm. It can be downloaded from the Node.js homepage and is available for many operating systems.

3.3 Running Node.js code

3.3.1 Evaluating code in the Node.js REPL

The Node.js REPL (read-eval-print loop) is a command line where we can interactively evaluate Node.js code.

We can start the Node.js REPL in JavaScript strict mode (which is safer and switched on by default for code in ESM modules):

node --use_strict

If we run node without any arguments, the Node.js REPL does not use strict mode:


This is what using the Node.js REPL looks like (% is a Unix shell prompt, > is the Node.js REPL prompt):

% node
Welcome to Node.js v18.9.0.
Type ".help" for more information.
> path.join('dir', 'sub', 'file.txt')

All of Node’s built-in modules are available via global variables in the REPL: assert, path, fs, util, etc.

3.3.2 Quickly printing the result of a JavaScript expression

We can use the shell command node with the option --print (abbreviation: -p) to print the result of evaluating a JavaScript expression. Similarly to the REPL, all built-in modules are available via global variables. For example, the following command prints the path of the homedirectory and works on both Unixes and Windows:

node -p "os.homedir()"

For more information on this command line option, see §15.7.7 “node --eval and node --print.

3.3.3 Running modules with Node.js code

Take, for example, the following module:

// my-module.mjs
import * as os from 'node:os';

We can run it from a shell via:

node my-module.mjs

3.3.4 Running Node.js code that’s in the clipboard

We can also run Node.js code that we have copied to the clipboard. For example, we could copy the code of my-module.mjs from the previous section and run it like this on macOS:

pbpaste | node --input-type=module

Option --input-type=module tells Node.js to interpret the code it receives from standard input as a module. Among other things, that enables us to use import.

The macOS shell command pbpaste sends the contents of the clipboard to standard output. Other operating systems have similar shell commands: