This chapter explains the first steps with Node.js.
node -h
node -v
npm version
node -p process.versions
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.
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:
node
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')
'dir/sub/file.txt'
>
All of Node’s built-in modules are available via global variables in the REPL: assert
, path
, fs
, util
, etc.
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
”.
Take, for example, the following module:
// my-module.mjs
import * as os from 'node:os';
console.log(os.userInfo());
We can run it from a shell via:
node my-module.mjs
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:
powershell get-clipboard
get-clipboard
xclip