Elijah Asaolu I am a programmer, I have a life.

Creating a custom REPL for Node.js

3 min read 1014

Creating a Custom REPL in Node.js

Introduction

Read–eval–print loop (REPL) is a term that refers to an interactive computer environment that takes the user input, executes it, and returns an output. I.e., the user enters one or more expressions, these expressions are evaluated, and a result is displayed.

Fact is, as a developer, you’ve probably used a REPL environment before now without knowing what it’s called. Common examples of REPL include:

  • CLI/terminals
  • Shell environments (e.g., Python shell, MySQL shell)
  • Browser devtool consoles

In this article, we will be learning how a REPL works internally, how to use the Node.js inbuilt REPL, and finally how to set up a customized REPL environment in Node.js.

How REPL works

The idea behind how a REPL works is quite straightforward. First, it reads a piece or block of code entered by the user, then it evaluates this code. After the evaluation process is completed, the resulting output is printed to the user, and this process is repeated (looped) until the user signals to quit.

Read-Eval-Print Loop

The Node.js REPL

Node.js is 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 this, you’ll need to have Node.js installed on your development machine; you can install Node.js by following the instructions here.

If you already have Node.js installed, you do not need to install any additional software, and you can start the REPL environment by entering the command below in your terminal:

node

Depending on the version of Node you have installed, you should see an output that is similar to the one below:

Node.js Startup Environment

The > sign displayed in the console signifies that the REPL is now active, and you can enter any JavaScript code to be immediately evaluated.

Let us try this out by using the global console.log method to print “Hello world.” Enter the code below in your Node REPL:

console.log("Hello World 👋");

You should see the following output displayed:

Node.js Consol Log

Creating a Custom REPL in Node.js

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

Also, this is an inbuilt module. I.e., we can use it without any further installation.

To import the module in our program:

const repl = require('repl');

Starting a REPL

We can create a new repl instance with the repl.start() method. This method accepts two parameters — the first is the string that is used for the prompt of your REPL (and this defaults to >), while the second is the stream (user input) that the REPL listens to.

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

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

Save the file, and from your CLI, run the code:

node app.js

You should see the following output:

Node REPL.js App

And, yes, this works the same way as the default Node REPL. You can try entering basic JavaScript code — like console.log("Hello world") — in your REPL, and you should see the output displayed.

Global and local scope

By default, the new REPL instance has access to all variables declared in Node.js global scope, and it is also possible to expose a local variable to REPL by explicitly assigning it 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;

Also, variables exposed to repl context are not read-only by default, and they can be modified directly from the REPL environment. We can change this by defining the context properties like below:

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,
});

Custom evaluation functions

The REPL module also lets you create a custom evaluation function; i.e., the function to be used when evaluating each given line of input. This can be handy when you are trying to build fully customized REPL applications.

Below is an example that checks if the user input is an even or odd number and prints the respective 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 });

Customizing REPL output

We can also customize the outputs returned from our REPL by passing in a new function for the writer option while creating a new repl instance.



The code below capitalizes the output returned from our previous example, and using npm colors.js module, it 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;
}

And here’s what the output looks like:

Custom Node.js REPL Output

Closing a REPL

While you can stop the REPL environment from running by pressing the Ctrl+C key or entering the .exit command directly, you can also do this programmatically with the repl.close() method:

Below is an example that closes the REPL automatically after five seconds:

const repl = require("repl");

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

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

Conclusion

REPL is an interactive computer environment that takes the user input, executes it, and returns an output. REPL is also a great alternative to text editors if you’re looking toward exploring code samples without having to store them in a file.

And in this article, we learned how a REPL works internally, how to use the Node inbuilt REPL environment, and finally how to create a custom REPL in Node.js.

200’s only Monitor failed and slow network requests in production

Deploying a Node-based web app or website is the easy part. Making sure your Node instance continues to serve resources to your app is where things get tougher. If you’re interested in ensuring requests to the backend or third party services are successful, try LogRocket. https://logrocket.com/signup/

LogRocket is like a DVR for web and mobile apps, recording literally everything that happens while a user interacts with your app. Instead of guessing why problems happen, you can aggregate and report on problematic network requests to quickly understand the root cause.

LogRocket instruments your app to record baseline performance timings such as page load time, time to first byte, slow network requests, and also logs Redux, NgRx, and Vuex actions/state. .
Elijah Asaolu I am a programmer, I have a life.

Leave a Reply