How to create your custom Node.js REPL

This post is part of my Today I learned series in which I share all my learnings regarding web development.

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:

const repl = require ( 'repl' ) ; const state = { printSomething ( ) { console . log ( "That's awesome!" ) ; } } ; const myRepl = repl . start ( "stefan's repl > " ) ; Object . assign ( myRepl . context , state ) ;

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.

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