Nodejs – REPL

The REPL(Read-Eval-Print-Loop) provides an interactive environment to interact with the core Nodejs module.

It’s a handy utility to test small snippets and explore various Nodejs packages from command line.

Starting REPL

The simplest way to start this REPL shell is by using node command as follows:

The other tab shows some of the useful commands available in REPL just for reference.

F:\nodejs\repl>node
Welcome to Node.js v12.18.3.
Type ".help" for more information.
>
> .help
.break    Sometimes you get stuck, this gets you out
.clear    Alias for .break
.editor   Enter editor mode
.exit     Exit the repl
.help     Print this help message
.load     Load JS from a file into the REPL session
.save     Save all evaluated commands in this REPL session to a file

Press ^C to abort current expression, ^D to exit the repl

 

This internally starts repl.REPLServer. We can also start instances of this server inside our programs by importing the following module.

const repl = require('repl');

As we will see at the end, we can start multiple instances to work on the same Nodejs process. But, to start with lets see some of the useful features we can get out of this REPL servers.

 

1. Evaluate Commands on REPL

We can use it for evaluating simple single or multi-line commands and functions on Nodejs.

> 5+5
10

> throw new Error("Oops...");
Uncaught Error: Oops...

> _error.message     //Shows last seen error message
'Oops...'
>
> function hello(name){
... console.log("Hello "+ name);
... }
undefined
> hello("Nodejs");
Hello Nodejs
undefined

Three dots shows the continuance of the same program in the next line.

REPL also provides autocomplete features while typing Nodejs commands.

 

2. Explore Global Objects

As shown below, we can explore the global objects in the Nodejs by using global. + [TAB] command.

> global.
global.__defineGetter__      global.__defineSetter__      global.__lookupGetter__      global.__lookupSetter__      global.__proto__
global.hasOwnProperty        global.isPrototypeOf         global.propertyIsEnumerable  global.toLocaleString        global.toString
global.valueOf

global.constructor

global.Array                 global.ArrayBuffer           global.Atomics               global.BigInt                global.BigInt64Array
global.BigUint64Array        global.Boolean               global.Buffer                global.DataView              global.Date
global.Error                 global.EvalError             global.Float32Array          global.Float64Array          global.Function
global.GLOBAL                global.Infinity              global.Int16Array            global.Int32Array            global.Int8Array
global.Intl                  global.JSON                  global.Map                   global.Math                  global.NaN
global.Number                global.Object                global.Promise               global.Proxy                 global.RangeError
global.ReferenceError        global.Reflect               global.RegExp                global.Set                   global.SharedArrayBuffer
global.String                global.Symbol                global.SyntaxError           global.TextDecoder           global.TextEncoder
global.TypeError             global.URIError              global.URL                   global.URLSearchParams       global.Uint16Array
global.Uint32Array           global.Uint8Array            global.Uint8ClampedArray     global.WeakMap               global.WeakSet
global.WebAssembly           global._                     global._error                global.assert                global.async_hooks
global.buffer                global.child_process         global.clearImmediate        global.clearInterval         global.clearTimeout
global.cluster               global.console               global.crypto                global.decodeURI             global.decodeURIComponent
global.dgram                 global.dns                   global.domain                global.encodeURI             global.encodeURIComponent
global.escape                global.eval                  global.events                global.fs                    global.global
global.globalThis            global.http                  global.http2                 global.https                 global.inspector
global.isFinite              global.isNaN                 global.module                global.net                   global.os
global.parseFloat            global.parseInt              global.path                  global.perf_hooks            global.process
global.punycode              global.querystring           global.queueMicrotask        global.readline              global.repl
global.require               global.root                  global.setImmediate          global.setInterval           global.setTimeout
global.stream                global.string_decoder        global.tls                   global.trace_events          global.tty
global.undefined             global.unescape              global.url                   global.util                  global.v8
global.vm                    global.worker_threads        global.zlib

 

3. Explore Packages

We can explore the constants and functions available in a Nodejs module as shown for file system(fs) module.

> fs.
fs.__defineGetter__      fs.__defineSetter__      fs.__lookupGetter__      fs.__lookupSetter__      fs.__proto__             fs.constructor
fs.hasOwnProperty        fs.isPrototypeOf         fs.propertyIsEnumerable  fs.toLocaleString        fs.toString              fs.valueOf

fs.Dir                   fs.Dirent                fs.F_OK                  fs.FileReadStream        fs.FileWriteStream       fs.R_OK
fs.ReadStream            fs.Stats                 fs.W_OK                  fs.WriteStream           fs.X_OK                  fs._toUnixTimestamp
fs.access                fs.accessSync            fs.appendFile            fs.appendFileSync        fs.chmod                 fs.chmodSync
fs.chown                 fs.chownSync             fs.close                 fs.closeSync             fs.constants             fs.copyFile
fs.copyFileSync          fs.createReadStream      fs.createWriteStream     fs.exists                fs.existsSync            fs.fchmod
fs.fchmodSync            fs.fchown                fs.fchownSync            fs.fdatasync             fs.fdatasyncSync         fs.fstat
fs.fstatSync             fs.fsync                 fs.fsyncSync             fs.ftruncate             fs.ftruncateSync         fs.futimes
fs.futimesSync           fs.lchmod                fs.lchmodSync            fs.lchown                fs.lchownSync            fs.link
fs.linkSync              fs.lstat                 fs.lstatSync             fs.mkdir                 fs.mkdirSync             fs.mkdtemp
fs.mkdtempSync           fs.open                  fs.openSync              fs.opendir               fs.opendirSync           fs.promises
fs.read                  fs.readFile              fs.readFileSync          fs.readSync              fs.readdir               fs.readdirSync
fs.readlink              fs.readlinkSync          fs.readv                 fs.readvSync             fs.realpath              fs.realpathSync
fs.rename                fs.renameSync            fs.rmdir                 fs.rmdirSync             fs.stat                  fs.statSync
fs.symlink               fs.symlinkSync           fs.truncate              fs.truncateSync          fs.unlink                fs.unlinkSync
fs.unwatchFile           fs.utimes                fs.utimesSync            fs.watch                 fs.watchFile             fs.write
fs.writeFile             fs.writeFileSync         fs.writeSync             fs.writev                fs.writevSync

 

4. Customize REPL

As mentioned above, we can also create the repl server instance using the repl module. Here, is an example of customizing the repl console :

  1. We have customized the prompt
  2. We have initialized the repl context with a variable and
  3. Finally, we have also added a new function to it.
const repl = require('repl');

function initializeContext(context) {
  context.desc = 'My REPL Console';
}

const replServer = repl.start({ prompt: 'My REPL ==> ' });
initializeContext(replServer.context);

replServer.defineCommand('bye', () => {
  console.log('bye bye!');
  replServer.close();
});
F:\nodejs\repl>node create-repl-server-02.js
My REPL ==> desc
'My REPL Console'
My REPL ==>
My REPL ==> 2+5
7
My REPL ==> .bye
bye bye!