Introduction
REPL stands for Read-Evaluate-Print-Loop. REPL provides a programming environment to quickly explore features provided by Nodejs:
Nodejs scripts
The node command is used to run Nodejs scripts:
node script.js
Starting a REPL session
The node command without any other argument provided starts a REPL session:
node
Trying this on your terminal:
node
>
Type some JavaScript and press enter:
node
> console.log('hello world!')
hello world!
undefined
The first line is the output from running console.log('hello world') and undefined is the return value for running console.log statement.
Running any expression from the REPL:
node
> ['cow', 'goat'].length === 2
true
Multi-line expressions
REPL is smart enough to know we are writing a multi-line expression:
node
> function greet() {
...
REPL inserts indentation/ space to add our function body. Finishing the greet function and calling the function from the REPL:
node
> function greet(name) {
... console.log(`Hello!, my name is ${name} and I am a full-stack developer!`)
... }
> greet("Roseland")
Hello!, my name is Roseland and I am a full-stack developer!
undefined
undefined is the return value for console.log statement inside the greet function.
The Up/Down arrow key
Pressing the Up/Down key displays the previous expressions/statements executed by the REPL
dot commands
The REPL has some special (.) commands, which can be started with a .:
.help: Shows all help info for all the dot commands.editor: opens a multiline editor mode to write multiline JavaScript with ease. Once done editing, hitctrl-D(CTRL key and D key simultaneously) to run the code.break: same asctrl-C, typing .break while in.editormode prevents further input.clear: resets the REPL history/contents and clears any multiline expression being input.load: loads a JavaScript file, relative to the current working directory from which the REPL is executed from.save: saves all REPL sessions to a file(specify the filename).exit: exits the REPL session, same as pressingctrl-ctwice
The node:repl module
A Nodejs REPL module exists for advanced use cases. Check out the REPL module here
Found this article helpful? You may follow me on Twitter where I tweet about interesting topics on software development.