Tutorials Logic
Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

Node.js REPL — Interactive Shell Guide

Node.js REPL

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 CaseExample
Learn JavaScript behaviorTest arrays, objects, strings, dates, and functions.
Explore Node.js APIsTry path, os, url, crypto, and fs.
Debug small transformationsCheck string cleanup, regex, number conversion, and JSON parsing.
Inspect package behaviorRequire or import an installed npm package.
Prototype functionsWrite a small function before moving it into a file.
Practice async codeUse 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
node
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.

CommandPurpose
nodeStart the standard REPL.
node --versionShow 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/configPreload 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
> const user = "Asha"
undefined

> user
'Asha'

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

> square(9)
81

REPL Context and Variables

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
> 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
> 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
> .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.

CommandDescription
.helpShow available REPL commands.
.exitExit the REPL.
.breakCancel current multi-line input.
.clearReset the REPL context in many cases.
.editorEnter editor mode for longer snippets.
.save file.jsSave current REPL session commands to a file.
.load file.jsLoad 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
> 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.

ShortcutPurpose
Up / Down arrowsMove through command history.
TabAutocomplete names or show object properties.
Ctrl + CCancel current input; press twice to exit.
Ctrl + DExit REPL or run editor mode input on many systems.

The Last Result Variable

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 _
> 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
> 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
> 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
> 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
npm install dayjs
node
> 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
> 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' ] }

Practical Debugging Workflows

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
> 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.

FeatureNode.js REPLBrowser Console
RuntimeNode.jsBrowser JavaScript engine
File systemAvailable through fsNot directly available
DOMNot available by defaultAvailable through document
Global objectglobalwindow or globalThis
Best forServer-side JavaScript and Node APIsWeb 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 WhenUse 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
const repl = require("node:repl");

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

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

Security and Safety Notes

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.

Common Mistakes to Avoid
WRONG Expect browser globals like window and document
RIGHT Remember that the REPL runs in Node.js
Node.js has server-side globals and modules; browser DOM APIs are not available by default.
WRONG Think undefined always means an error
RIGHT Understand that declarations often print undefined
Type the variable name after declaring it to inspect the value.
WRONG Keep large reusable programs inside the REPL
RIGHT Move useful code into files
The REPL is a scratchpad; project files are better for real work.
WRONG Use _ for important long-term values
RIGHT Use named variables
The underscore value changes whenever a new expression is evaluated.
WRONG Paste unknown code into the REPL
RIGHT Review code before running it
REPL commands can read files, write files, access environment variables, and run package code.
Key Takeaways
  • REPL stands for Read, Eval, Print, Loop.
  • Start the Node.js REPL by typing node in a terminal.
  • The REPL is useful for learning, quick testing, debugging, and module exploration.
  • Dot commands such as .help, .exit, .save, .load, and .editor control the session.
  • Use require() for CommonJS modules and dynamic import() for ES modules.
  • Modern Node.js supports top-level await in the REPL.
  • Use the REPL as a scratchpad, then move useful code into project files.

Frequently Asked Questions


Ready to Level Up Your Skills?

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