Using Node CLI and REPL

CLI stands for command-line interface and REPL stands for Read Eval Print and Loop. Almost every programming language/environment or even framework provides REPL to play around with the features available.

In this article, we will be using NodeJs REPL to get started with NodeJs.

Lets Start

node

You will get a screen something like

image.png

Autocomplete

NodeJs REPL allows autocompleting out of the box.

hit tab (2) times

You will see the huge list of the modules available on NodeJs. Something similar to this

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

__proto__             hasOwnProperty        isPrototypeOf         propertyIsEnumerable  toLocaleString
toString              valueOf

constructor

global

We can find all the properties of global object with

global. +(tab)

List will look similar to

global.__proto__             global.hasOwnProperty        global.isPrototypeOf         global.propertyIsEnumerable
global.toLocaleString        global.toString              global.valueOf

global.constructor

global.AbortController       global.AbortSignal           global.AggregateError        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.Event
global.EventTarget           global.FinalizationRegistry  global.Float32Array          global.Float64Array
global.Function              global.Infinity              global.Int16Array            global.Int32Array
global.Int8Array             global.Intl                  global.JSON                  global.Map
global.Math                  global.MessageChannel        global.MessageEvent          global.MessagePort
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.WeakRef               global.WeakSet               global.WebAssembly
global._                     global._error                global.assert                global.async_hooks
global.atob                  global.btoa                  global.buffer                global.child_process
global.clearImmediate        global.clearInterval         global.clearTimeout          global.cluster
global.console               global.constants             global.crypto                global.decodeURI
global.decodeURIComponent    global.dgram                 global.diagnostics_channel   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.performance           global.process
global.punycode              global.querystring           global.queueMicrotask        global.readline
global.repl                  global.require               global.setImmediate          global.setInterval
global.setTimeout            global.stream                global.string_decoder        global.sys
global.timers                global.tls                   global.trace_events          global.tty
global.undefined             global.unescape              global.url                   global.util
global.v8                    global.vm                    global.wasi                  global.worker_threads
global.zlib

All of these are the top-level objects and modules available on the global object.

Remember: Some of them can not be used on the code you will write.

You can always do console.log(global) to see what you can use on your codebase.

<ref *1> Object [global] {
  global: [Circular *1],
  clearInterval: [Function: clearInterval],
  clearTimeout: [Function: clearTimeout],
  setInterval: [Function: setInterval],
  setTimeout: [Function: setTimeout] {
    [Symbol(nodejs.util.promisify.custom)]: [Getter]
  },
  queueMicrotask: [Function: queueMicrotask],
  clearImmediate: [Function: clearImmediate],
  setImmediate: [Function: setImmediate] {
    [Symbol(nodejs.util.promisify.custom)]: [Getter]
  }
}

Autocomplete works for any object.

Array

Let's create an empty array to see what functions are available on the array object.

const arr = [];

// And
arr.+(tab)

You can find a list of something like

arr.__defineGetter__      arr.__defineSetter__      arr.__lookupGetter__      arr.__lookupSetter__
arr.__proto__             arr.hasOwnProperty        arr.isPrototypeOf         arr.propertyIsEnumerable
arr.valueOf

arr.concat                arr.constructor           arr.copyWithin            arr.entries
arr.every                 arr.fill                  arr.filter                arr.find
arr.findIndex             arr.flat                  arr.flatMap               arr.forEach
arr.includes              arr.indexOf               arr.join                  arr.keys
arr.lastIndexOf           arr.map                   arr.pop                   arr.push
arr.reduce                arr.reduceRight           arr.reverse               arr.shift
arr.slice                 arr.some                  arr.sort                  arr.splice
arr.toLocaleString        arr.toString              arr.unshift               arr.values

arr.length

You can also have some starting characters autocomplete

arr.co + (tab)

The output will look something like

arr.concat       arr.constructor  arr.copyWithin

Saving previous value on REPL

You can always create a variable and store the value on it. If you don't want to create a new variable each time you do some calculation, you can use _ to store the previous value.

For example, lets create a random number with Math.random().

Math.random()

And then

_

You will get previous output stored on _.

You can also use this value for further calculation.

_ * 10

All together ( Values can be different on yours)


> Math.random()
0.5641577091577177
> _
0.5641577091577177
> _ * 10
5.641577091577177
> _
5.641577091577177
>

Special commands

You can get special command with . (period sign) + tab.

. + (tab)

A list of special commands will be listed like:

break   clear   editor  exit    help    load    save

You can use any of these commands preceding with .. In our case since we are wrapping this article here, we will be using .exit.

.exit

Thank you!!!