Tutorials Logic, IN info@tutorialslogic.com

Node.js REPL Interactive Shell

REPL Setup and Evaluation

The Node.js REPL reads one input, evaluates it in the current session, prints the result, and repeats. It is useful for inspecting APIs and testing isolated expressions.

REPL stands for Read, Eval, Print, Loop. It is the interactive JavaScript shell that comes with Node.js. The REPL lets you type JavaScript and Node.js code directly in the terminal and immediately see the result.

Instead of creating a file, saving it, and running node app.js, you can open the REPL and test expressions, variables, functions, modules, regular expressions, JSON, promises, and built-in Node.js APIs one step at a time. It is a practical scratchpad for learning, debugging, and exploring.

  • Read: Node reads your input.
  • Eval: Node evaluates the JavaScript.
  • Print: Node prints the result.
  • Loop: Node waits for the next command.

Why Use the REPL?

The REPL is useful when you want quick feedback. It is not a replacement for real project files, but it is excellent for testing small pieces of logic before writing permanent code.

Use Case Example
Learn JavaScript behavior Test arrays, objects, strings, dates, and functions.
Explore Node.js APIs Try path, os, url, crypto, and fs.
Debug small transformations Check string cleanup, regex, number conversion, and JSON parsing.
Inspect package behavior Require or import an installed npm package.
Prototype functions Write a small function before moving it into a file.
Practice async code Use top-level await for promises and dynamic imports.

Starting the Node.js REPL

Open a terminal and type node. If Node.js is installed correctly, the terminal will show a > prompt.

Start REPL

Start REPL
node

First REPL Examples

First REPL Examples
> 10 + 20
30

> "node".toUpperCase()
'NODE'

> [1, 2, 3].map(n => n * 2)
[ 2, 4, 6 ]

Useful Startup Options

You can start Node with flags that change REPL behavior or preload code. These options are useful when experimenting with a project.

Command Purpose
node Start the standard REPL.
node --version Show installed Node.js version.
node -e "console.log(2 + 3)" Evaluate one expression from the terminal.
node -i -e "const appName = 'Demo'" Run code and stay in interactive mode.
node -r dotenv/config Preload a module before entering the REPL.

Expressions, Statements, and undefined

Expressions produce values, so the REPL prints them. Statements such as variable declarations often print undefined. That does not mean the command failed; it only means the statement did not produce a display value.

Variables and Functions

Variables and Functions
> const user = "Asha"
undefined

> user
'Asha'

> function square(number) {
...   return number * number;
... }
undefined

> square(9)
81

Session Editing and Commands

Variables you create in the REPL stay available during the current session. This makes the REPL useful for building a small experiment step by step.

Session Context

Session Context
> const cart = []
undefined

> cart.push({ name: "Book", price: 499 })
1

> cart.push({ name: "Pen", price: 20 })
2

> cart.reduce((sum, item) => sum + item.price, 0)
519

Multi-Line Input

When your input is incomplete, the REPL continues with .... This lets you write arrays, objects, functions, loops, conditionals, classes, and template literals over multiple lines.

Multi-Line Code

Multi-Line Code
> const users = [
...   { name: "Asha", active: true },
...   { name: "Ravi", active: false },
...   { name: "Meera", active: true }
... ]
undefined

> users.filter(user => user.active).map(user => user.name)
[ 'Asha', 'Meera' ]

Editor Mode

For longer snippets, use .editor. It opens a small editor-style input area inside the terminal. After writing the code, press Ctrl + D on many systems to execute it.

Editor Mode - JavaScript Example

Editor Mode - JavaScript Example
> .editor
// Entering editor mode
function createSlug(title) {
  return title
    .toLowerCase()
    .trim()
    .replaceAll(" ", "-");
}

createSlug("Node JS REPL Tutorial")
// Press Ctrl + D to run

Dot Commands

Dot commands are special REPL commands. They are not JavaScript syntax, so they only work inside the REPL.

Command Description
.help Show available REPL commands.
.exit Exit the REPL.
.break Cancel current multi-line input.
.clear Reset the REPL context in many cases.
.editor Enter editor mode for longer snippets.
.save file.js Save current REPL session commands to a file.
.load file.js Load JavaScript from a file into the REPL.

Saving and Loading REPL Code

If an experiment becomes useful, you can save the REPL input to a file. You can also load a file into the REPL to continue experimenting with it.

Save and Load

Save and Load
> function add(a, b) { return a + b; }
undefined

> add(2, 3)
5

> .save scratch.js
Session saved to: scratch.js

> .load scratch.js

History, Autocomplete, and Shortcuts

The REPL keeps command history and supports autocomplete. These features make it faster to explore objects and repeat previous commands.

Shortcut Purpose
Up / Down arrows Move through command history.
Tab Autocomplete names or show object properties.
Ctrl + C Cancel current input; press twice to exit.
Ctrl + D Exit REPL or run editor mode input on many systems.

Values, Modules, and Packages

The special variable _ stores the result of the previous expression. It is useful for quick calculations, but named variables are clearer for serious work.

Using _

Using _
> 50 / 2
25

> _ + 10
35

> _.toString()
'35'

Using CommonJS Modules

Node.js built-in modules and many packages can be loaded with require(). This is useful for exploring APIs interactively.

require() in REPL

require() in REPL
> const path = require("node:path")
undefined

> path.basename("/projects/app/server.js")
'server.js'

> const os = require("node:os")
undefined

> os.platform()
'win32'

Using ES Modules and Dynamic import()

Modern Node.js supports dynamic import() in the REPL. This is useful for ES modules, promise-based APIs, and packages that do not support require().

Dynamic Import

Dynamic Import
> const fs = await import("node:fs/promises")
undefined

> typeof fs.readFile
'function'

> const { URL } = await import("node:url")
undefined

> new URL("https://example.com/docs?page=1").searchParams.get("page")
'1'

Async and Promises in the REPL

The REPL supports top-level await in modern Node.js. This makes it easy to test promise-based APIs without wrapping code in an async function.

Top-Level await

Top-Level await
> await Promise.resolve("done")
'done'

> const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
undefined

> await delay(500)
undefined

Using npm Packages in the REPL

If a package is installed in the current project, you can load it in the REPL from that project directory. This is helpful for testing package APIs before using them in application code.

Installed Package Example

Installed Package Example
npm install dayjs
node

Using npm Packages in the REPL - JavaScript Example

Using npm Packages in the REPL - JavaScript Example
> const dayjs = require("dayjs")
undefined

> dayjs("2026-05-08").format("DD MMM YYYY")
'08 May 2026'

Inspecting Objects

The REPL is excellent for inspecting objects. You can use console.log(), console.dir(), Object.keys(), and autocomplete to explore available properties and methods.

Object Inspection

Object Inspection
> const user = { name: "Asha", skills: ["HTML", "CSS", "Node.js"] }
undefined

> Object.keys(user)
[ 'name', 'skills' ]

> console.dir(user, { depth: null })
{ name: 'Asha', skills: [ 'HTML', 'CSS', 'Node.js' ] }

Debugging and Custom REPLs

The REPL is ideal for isolating one small part of a problem. You can test transformations separately before changing your real application.

String, Regex, and JSON Checks

String, Regex, and JSON Checks
> const rawTitle = "  Node.js REPL Tutorial  "
undefined

> rawTitle.trim().toLowerCase().replaceAll(" ", "-")
'node.js-repl-tutorial'

> const price = "$1,499"
undefined

> Number(price.replace(/[$,]/g, ""))
1499

> JSON.parse('{"active":true,"count":3}')
{ active: true, count: 3 }

REPL vs Browser Console

Node.js REPL and the browser console both run JavaScript, but they run in different environments. Browser APIs are not automatically available in Node.js, and Node.js APIs are not automatically available in the browser.

Feature Node.js REPL Browser Console
Runtime Node.js Browser JavaScript engine
File system Available through fs Not directly available
DOM Not available by default Available through document
Global object global window or globalThis
Best for Server-side JavaScript and Node APIs Web page debugging and DOM inspection

REPL vs Script Files

The REPL is best for exploration. Script files are best for repeatable, testable, maintainable code.

Use REPL When Use a File When
You are testing one small idea. You need repeatable code.
You are exploring a module. You are building a project feature.
You want immediate feedback. You need formatting, tests, imports, and version control.
You are debugging a small expression. The code has multiple functions or modules.

Custom REPL with the repl Module

Node.js also provides a built-in repl module. You can use it to create a custom interactive shell for your application, expose helper variables, or build internal developer tools.

Custom REPL

Custom REPL
const repl = require("node:repl");

const server = repl.start({
  prompt: "app> "
});

server.context.appName = "Tutorial App";
server.context.add = (a, b) => a + b;

REPL Security and Completion

The REPL can run any JavaScript code with the permissions of your terminal process. Be careful when pasting code from unknown sources, loading packages, or experimenting in production directories.

  • Do not paste untrusted commands into the REPL.
  • Do not expose a custom REPL publicly.
  • Be careful with file system and database commands.
  • Use a scratch project when testing unfamiliar packages.
  • Move useful experiments into files and review them before reuse.

Conclusion

The Node.js REPL is a fast and practical environment for interactive JavaScript. It helps you learn syntax, inspect values, test functions, explore modules, use async APIs, debug transformations, and prototype small ideas without creating a full project file.

Use the REPL as a scratchpad for discovery. When the code becomes important, repeatable, or part of a real application, move it into a proper file with formatting, tests, and version control.

Evaluation and Safety Review

The Node REPL reads JavaScript, evaluates it in a persistent context, prints the result, and repeats. Definitions survive across entries until cleared, so a later command may depend on hidden state. Use `.clear` or start a fresh session when verifying a minimal reproduction.

Top-level await, dynamic import, multiline input, underscore result variables, and completion make the REPL useful for checking runtime behavior quickly. Results reflect the installed Node version and current working directory; record both when an experiment informs production code.

REPL output uses inspection rules rather than JSON serialization. Circular objects, getters, custom inspection hooks, maps, and buffers may display differently from application responses. Move any important discovery into a script and automated test before treating it as a stable contract.

  • Reset hidden session state before a reproducibility check.
  • Record runtime version and working directory.
  • Do not confuse inspected output with serialization.
  • Promote useful experiments into source and tests.

REPL Safety

A REPL executes code with the permissions of its process. Do not paste unreviewed commands, tokens, private records, or destructive database operations into a production-connected shell. History files, terminal capture, and copied output can retain secrets long after the session closes.

Use disposable local data and a least-privilege environment. Prefer a script with review, dry-run behavior, structured input, and an audit trail for repeatable administration. Disable or tightly protect any remote REPL or inspector endpoint; exposing one is effectively remote code execution.

Use `.help`, `.editor`, `.load`, `.save`, `.break`, and `.exit` deliberately, and understand that loaded files run in the current session. When debugging an application, attach through approved tooling and reproduce the issue without changing live state unless the incident procedure explicitly permits it.

  • Treat REPL access as code-execution authority.
  • Keep secrets out of history and captured output.
  • Use scripts for reviewed repeatable operational work.
  • Never expose an unauthenticated remote REPL or inspector.
Before you move on

Node.js REPL Interactive Shell Mastery Check

5 checks
  • REPL stands for Read, Eval, Print, Loop.
  • It is the interactive JavaScript shell that comes with Node.js.
  • The REPL lets you type JavaScript and Node.js code directly in the terminal and immediately see the result.
  • It is a practical scratchpad for learning, debugging, and exploring.
  • The REPL is useful when you want quick feedback.

Node JS Questions Learners Ask

The REPL prints the result of the expression or statement you entered.

The REPL is an interactive session with conveniences such as the last-result variable, relaxed experimentation, and a persistent session context.

Top-level await lets you test promise-based code without wrapping it in an async function. That is handy for trying fetch calls, dynamic imports, database helper functions, or filesystem promises during debugging.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.