DEV Community

Stefan Judis
Stefan Judis

Posted on • Originally published at stefanjudis.com on

TIL: How to create your custom Node.js REPL

Today I came across a quick video which explains functionality about Node.js and its REPL (Read-Eval-Print loop).

While I use the built-in REPL from time to time (type node into your terminal to start it) I haven't used the REPL module before. It turns out that you can create your custom REPL with just a few lines of JavaScript:

// index.js
const repl = require('repl');

const state = {
  printSomething() {
    console.log("That's awesome!");
  }
};

const myRepl = repl.start("stefan's repl > ");

Object.assign(myRepl.context, state);
Enter fullscreen mode Exit fullscreen mode

If you're like me and like to prototype in a console, this can become very handy. You could create an entry script for your application that provides all the initialized objects and functionality.

Screenshot of a terminal: start a new REPL by running "node index.js" and see the available command 'printSomething'

By providing your own REPL that includes all the needed state you can "just REPL away" without starting a debugger and attaching breakpoints. 🎉

Top comments (0)