1 min read

REPL in Node JS

The repl module provides a Read-Eval-Print-Loop (REPL) implementation that is available both as a standalone program or includible in other applications. It can be accessed using: const repl = require('repl');
REPL in Node JS

Design and features

The repl module exports the repl.REPLServer class. While running, instances of repl.REPLServer will accept individual lines of user input, evaluate those according to a user-defined evaluation function, then output the result. Input and output may be from stdin and stdout, respectively, or may be connected to any Node.js stream.

Instances of repl.REPLServer support automatic completion of inputs, completion preview, simplistic Emacs-style line editing, multi-line inputs, ZSH-like reverse-i-search, ZSH-like substring-based history search, ANSI-styled output, saving and restoring current REPL session state, error recovery, and customizable evaluation functions. Terminals that do not support ANSI styles and Emacs-style line editing automatically fall back to a limited feature set.

Commands and special keys

The following special commands are supported by all REPL instances:

  • .break: When in the process of inputting a multi-line expression, enter the .break command (or press Ctrl+C) to abort further input or processing of that expression.
  • .clear: Resets the REPL context to an empty object and clears any multi-line expression being input.
  • .exit: Close the I/O stream, causing the REPL to exit.
  • .help: Show this list of special commands.
  • .save: Save the current REPL session to a file: > .save ./file/to/save.js
  • .load: Load a file into the current REPL session. > .load ./file/to/load.js
  • .editor: Enter editor mode (Ctrl+D to finish, Ctrl+C to cancel).

Example

> .editor
// Entering editor mode (^D to finish, ^C to cancel)
function welcome(name) {
  return `Hello ${name}!`;
}

welcome('Node.js User');
JavaScript expressions

The default evaluator supports direct evaluation of JavaScript expressions:

> 1 + 1
2
> const m = 2
undefined
> m + 1
3
REPL | Node.js v16.3.0 Documentation
https://nodejs.org/api/repl.html

#JavaScript #NodeJS #REPL #Probyto #ProbytoAI

Subscribe and follow us for latest news in Data Science and Machine learning and stay updated!

Facebook: https://facebook.com/probyto
Twitter: https://twitter.com/probyto
LinkedIn: https://linkedin.com/company/probyto
Instagram: https://instagram.com/probyto