Introduction to the

Read comment Print loop (REPL) is a term for an interactive computer environment that takes user input, executes it, and returns output. That is, the user enters one or more expressions, which are evaluated, and a result is displayed.

The truth is, as a developer, you’ve probably used the REPL environment before, but have no idea what it’s called. Common examples of REPL include.

  • CLI/terminals
  • Shell environment (e.g., Python shell, MySQL shell
  • Browser Devtool console

In this article, we’ll learn the inner workings of a REPL, how to use the built-in REPL in Node.js, and finally how to set up a custom REPL environment in Node.js.

How does the REPL work

How the REPL works is pretty straightforward. First, it reads a piece or block of code entered by the user, and then evaluates that code. After the evaluation process is complete, the resulting output is printed to the user, and the process is repeated (looped) until the user signals an exit.

Node. Js REPL

Node.js comes bundled with a REPL environment that allows you to quickly test and explore JavaScript code without having to store it in a file.

Before you can run the environment, you need to install Node.js on your development machine; You can install Node.js by following the instructions here.

If you already have Node.js installed, you don’t need to install any additional software, and you can start the REPL environment by typing the following command on the terminal.

node

Copy the code

Depending on what version of Node you have installed, you should see output similar to the following.

The **>** symbol displayed in the console is displayed in the console, indicating that the REPL is now active and you can enter any JavaScript code for immediate evaluation.

Let’s try it by printing “Hello World “using the global console.log method. Enter the following code in your Node REPL.

The console. The log (" Hello World 👋 ");Copy the code

You should see the output below.

Create a custom REPL in Node.js

Node.js also allows developers to create and use custom REPLs using the REPL module. This is the same package used to create the default REPL that comes with Node.js, so it does provide all the customizable options we might need.

Also, this is a built-in module. That is, we can use it without further installation.

To import this module into our program.

const repl = require('repl');

Copy the code

Start the REPL

We can create a new rep instance with the repl.start() method. This method takes two arguments – the first is the string for the REPL hint (default >), and the second is the stream the REPL is listening for (user input).

To try this out, create a new file (app.js) and paste the following code.

const repl = require("repl");
repl.start("custom-repl => ");

Copy the code

Save the file and run the code from your CLI.

node app.js

Copy the code

You should see the following output.

And, yes, this works the same way as the default Node REPL. You can try typing basic JavaScript code into the REPL — such as console.log(“Hello world”) — and you should see the output displayed.

Global and local scopes

By default, a new REPL instance can access all variables declared globally in Node.js, or it can be exposed to the REPL by explicitly assigning a local variable to the Context object.

const repl = require("repl"); /* this can be accessed directly from repl without exposing it to repl context */ global.globalVariable = "This can be accessed anywhere!" ; const name = "John Doe"; // exposing local variable to repl context repl.start("custom-repl => ").context.name = name;Copy the code

In addition, variables exposed in the REPL context are not read-only by default; they can be modified directly from the REPL environment. We can change this by defining context properties like the following.

const repl = require("repl");
const name = "John Doe";

const r = repl.start("custom-repl => ");

Object.defineProperty(r.context, "name", {
  configurable: false,
  enumerable: true,
  value: name,
});

Copy the code

Custom evaluation functions

The REPL module also allows you to create a custom evaluation function; The function used to evaluate each line of input. This can be handy when you’re trying to build a fully customized REPL application.

Here is an example that checks whether the user input is even or odd and prints the corresponding output based on the input.

const repl = require("repl");

function isEven(uInput, context, filename, callback) {
  callback(null, uInput % 2 == 0 ? "Even number" : "odd number");
}

repl.start({ prompt: "custom-repl => ", eval: isEven });

Copy the code

Customize the REPL output

We can also customize the output returned from our REPL by creating a new **writer** option along with a new REPL instance.

The following code capitalizes the output returned in our previous example and uses the npmcolors.js module, which also changes the text color to red.

const repl = require("repl");
const colors = require("colors");

const r = repl.start({ prompt: "custom-repl =>  ", eval: isEven, writer: modifyOutput });

function isEven(uInput, context, filename, callback) {
  callback(null, uInput % 2 == 0 ? "Even number" : "odd number");
}

function modifyOutput(output) {
  return output.toUpperCase().red;
}

Copy the code

Here’s what the output looks like.

Close the REPL

While you can stop the REPL environment by pressing Ctrl+C or simply typing the.exit command, you can also do this programmatically with the repl.close() method.

Here is an example of an automatic REPL shutdown after five seconds.

const repl = require("repl");

const r = repl.start("custom-repl => ");

setTimeout(() => {
  r.close();
}, 5000);

Copy the code

conclusion

REPL is an interactive computer environment that takes input from the user, executes it, and returns an output. REPL is also a good alternative to a text editor if you want to explore code samples without having to store them in files.

In this article, we learned about the inner workings of a REPL, how to use Node’s built-in REPL environment, and finally how to create a custom REPL in Node.js.

The postCreating a custom REPL for Node.jsappeared first onLogRocket Blog.