How to use the Node.js REPL
What is the Node.js REPL?
Node.js comes with a built-in REPL (Read-Eval-Print Loop) environment that allows you to execute JavaScript code interactively. The REPL is accessible through the terminal and is a great way to test out small pieces of code.
How to use the Node.js REPL
The node
command is the one we use to run our Node.js scripts:
node script.js
If we run the node
command without any script to execute or without any arguments, we start a REPL session:
node
Note:
REPL
stands for Read Evaluate Print Loop, and it is a programming language environment (basically a console window) that takes single expression as user input and returns the result back to the console after execution. The REPL session provides a convenient way to quickly test simple JavaScript code.
If you try it now in your terminal, this is what happens:
❯ node
>
The command stays in idle mode and waits for us to enter something.
Tip: if you are unsure how to open your terminal, google "How to open terminal on your-operating-system".
The REPL is waiting for us to enter some JavaScript code, to be more precise.
Start simple and enter
> console.log('test')
test
undefined
>
The first value, test
, is the output we told the console to print, then we get undefined
which is the return value of running console.log()
.
Node read this line of code, evaluated it, printed the result, and then went back to waiting for more lines of code. Node will loop through these three steps for every piece of code we execute in the REPL until we exit the session. That is where the REPL got its name.
Node automatically prints the result of any line of JavaScript code without the need to instruct it to do so. For example, type in the following line and press enter:
> 5 === '5'
false
>
Note the difference in the outputs of the above two lines. The Node REPL printed undefined
after executing console.log()
, while on the other hand, it just printed the result of 5 === '5'
. You need to keep in mind that the former is just a statement in JavaScript, and the latter is an expression.
In some cases, the code you want to test might need multiple lines. For example, say you want to define a function that generates a random number, in the REPL session type in the following line and press enter:
function generateRandom() {
...
The Node REPL is smart enough to determine that you are not done writing your code yet, and it will go into a multi-line mode for you to type in more code. Now finish your function definition and press enter:
function generateRandom() {
...return Math.random()
}
undefined
The _
special variable
If after some code you type _
, that is going to print the result of the last operation.
The Up arrow key
If you press the up
arrow key, you will get access to the history of the previous lines of code executed in the current, and even previous REPL sessions.
Dot commands
The REPL has some special commands, all starting with a dot .
. They are
.help
: shows the dot commands help.editor
: enables editor mode, to write multiline JavaScript code with ease. Once you are in this mode, enter ctrl-D to run the code you wrote..break
: when inputting a multi-line expression, entering the .break command will abort further input. Same as pressing ctrl-C..clear
: resets the REPL context to an empty object and clears any multi-line expression currently being input..load
: loads a JavaScript file, relative to the current working directory.save
: saves all you entered in the REPL session to a file (specify the filename).exit
: exits the repl (same as pressing ctrl-C two times)
The REPL knows when you are typing a multi-line statement without the need to invoke .editor
.
For example if you start typing an iteration like this:
[1, 2, 3].forEach(num => {
and you press enter
, the REPL will go to a new line that starts with 3 dots, indicating you can now continue to work on that block.
... console.log(num)
... })
If you type .break
at the end of a line, the multiline mode will stop and the statement will not be executed.
Run REPL from JavaScript file
We can import the REPL in a JavaScript file using repl
.
const module "node:repl"
repl = var require: NodeJS.Require
(id: string) => any
Used to import modules, `JSON`, and local files.require('node:repl');
Using the repl variable we can perform various operations. To start the REPL command prompt, type in the following line
repl.start();
Run the file in the command line.
node repl.js
You can pass a string which shows when the REPL starts. The default is '> ' (with a trailing space), but we can define custom prompt.
// a Unix style prompt
const const local: any
local = repl.start('$ ');
You can display a message while exiting the REPL
local.on('exit', () => {
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.log('exiting repl');
var process: NodeJS.Process
process.NodeJS.Process.exit(code?: number | string | null | undefined): never
The `process.exit()` method instructs Node.js to terminate the process
synchronously with an exit status of `code`. If `code` is omitted, exit uses
either the 'success' code `0` or the value of `process.exitCode` if it has been
set. Node.js will not terminate until all the `'exit'` event listeners are
called.
To exit with a 'failure' code:
```js
import { exit } from 'node:process';
exit(1);
```
The shell that executed Node.js should see the exit code as `1`.
Calling `process.exit()` will force the process to exit as quickly as possible
even if there are still asynchronous operations pending that have not yet
completed fully, including I/O operations to `process.stdout` and `process.stderr`.
In most situations, it is not actually necessary to call `process.exit()` explicitly. The Node.js process will exit on its own _if there is no additional_
_work pending_ in the event loop. The `process.exitCode` property can be set to
tell the process which exit code to use when the process exits gracefully.
For instance, the following example illustrates a _misuse_ of the `process.exit()` method that could lead to data printed to stdout being
truncated and lost:
```js
import { exit } from 'node:process';
// This is an example of what *not* to do:
if (someConditionNotMet()) {
printUsageToStdout();
exit(1);
}
```
The reason this is problematic is because writes to `process.stdout` in Node.js
are sometimes _asynchronous_ and may occur over multiple ticks of the Node.js
event loop. Calling `process.exit()`, however, forces the process to exit _before_ those additional writes to `stdout` can be performed.
Rather than calling `process.exit()` directly, the code _should_ set the `process.exitCode` and allow the process to exit naturally by avoiding
scheduling any additional work for the event loop:
```js
import process from 'node:process';
// How to properly set the exit code while letting
// the process exit gracefully.
if (someConditionNotMet()) {
printUsageToStdout();
process.exitCode = 1;
}
```
If it is necessary to terminate the Node.js process due to an error condition,
throwing an _uncaught_ error and allowing the process to terminate accordingly
is safer than calling `process.exit()`.
In `Worker` threads, this function stops the current thread rather
than the current process.exit();
});
You can read more about the REPL module in the repl documentation.