For enquiries call:

Phone

+1-469-442-0620

April flash sale-mobile

HomeBlogWeb DevelopmentNode.js REPL: Getting Started

Node.js REPL: Getting Started

Published
12th Oct, 2023
Views
view count loader
Read it in
12 Mins
In this article
    Node.js REPL: Getting Started

    Node.js is an Open-Source and Cross-platform JavaScript runtime environment built on V8 JavaScript engine – the core of google chrome. It is used to build high-performing and scalable applications and is an event-driven non-blocking I/O model.

    Introduction to REPL

    Node.js, when installed, comes with REPL environment which stands for READ, EVAL, PRINT, and LOOP which is similar to a computer environment like a command prompt or Shell. This environment interacts with the user writing or debugging through the outputs of his commands/expressions.

    To switch to this environment, open the terminal and enter ‘node’ text and press ‘Enter’ key. Let’s follow along with each keyword.

    • READ – User interacting with the environment writes the commands or expressions which are parsed into Java script data structure and store in memory.
    • EVAL – Output of READ i.e., parsed JavaScript data structure is evaluated to obtain the result.
    • PRINT – The result obtained from the EVAL is printed back to the environment for the user to read.
    • LOOP – The above three functions are executed in loop till the user exits/terminates from the environment by pressing Ctrl+C.
      • To exit in Terminal (mac), press Ctrl+C twice (or) Ctrl+D (or) .exit + Enter key.

    In terminal:

    machine-name ~ % node
    Welcome to Node.js v14.16.1.
    Type ".help" for more information.
    >

    As you can see from the above pic, REPL is demarcated by symbol ‘>’ once it is started. As a user, we can input any command or expression to get REPL.

    Note: Going forward we would be switching between node.js terminal and chrome console based on convenience, but both would mean the same.

    Decoding the REPL

    Understanding of REPL with simple variable

    Now let's start giving a few basic commands and understand how REPL works

    Invoke the REPL by entering the node and pressing the ‘enter’ key. You should be seeing the symbol ‘>’ ready to take input for evaluation.

    In browser console:

    > var greet = "Welcome to Node.Js REPL" 
    <. undefined 
    > greet 
    <. 'Welcome to Node.Js REPL' 
    > greet = "Good to see you here!" 
    <. 'Good to see you here!' 
    > greet 
    <. 'Good to see you here!' 
    >

    In the first line, we created a variable named greet with a value of ‘Welcome to Node.Js REPL’. REPL responded with undefined as the expression doesn’t return anything.

    Next, we entered the variable name ‘greet’ and REPL responded with the value stored in previous execution i.e., Welcome to Node.Js REPL.

    Post this, we tried reset the value of ‘greet’ variable with different text and on click on enter it responded with the new value in the ‘greet’. To recheck the value is set correctly, we re-entered the greet and REPL responded with the new value set i.e. ‘Good to see you here!’.

    Note: Output of the command is demarcated by symbol ‘<’ with dot in chrome and without symbol in terminal.

    Performing Arithmetic operations in REPL

    Let’s take another example where we want to perform some arithmetical operations in REPL.

    In browser console:

    > 1 + 1 // addition 
    <. 2 
    > 2 - 1 //subtraction 
    <. 1 
    > 2 * 2 // multiplication 
    <. 4 
    > 6 / 3 // division 
    <. 2 
    > 10 % 3 // remainder 
    <. 1 
    > 3 * 4 - 2 / 2 + 1 // follows BODMAS principle 
    <. 12 
    >

    In the above example we are able to perform different arithmetic operations individually and together. And from the last example, it is evident that REPL internally follows BODMAS principle for performing operations.

    In-built Math Module in REPL

    Node.js also comes with a library called Math which is used to perform some more complex operations. Let’s see few of them which are used more often in action.

    Examples of Math methods in the browser console:

    > Math.floor(4/3) // round to lower integer 
    <. 1 
    > Math.ceil(4/3) // round to closest higher integer 
    <. 2 
    > Math.round(4.6) // rounds to higher if decimal is greater than or equal to .5 otherwise to lower integer 
    <. 5 
    > Math.sqrt(4) // Square root 
    <. 2 
    > Math.pow(2, 3) // 2 raised to the power of 3. 
    <. 8 
    >

    Writing functions in REPL

    Till now we were using simple one-line expressions. Let’s try writing functions and get them executed as well. Let’s write a function which gives random number for a given maximum say 10, 100, 1000.

    > function getRandomNumber(max) { 
        let result = Math.random() * max; 
        return Math.floor(result); 
      } 
    <. undefined 
    >  getRandomNumber(10) 
    <. 1 
    >  getRandomNumber(10) 
    <. 7 
    >  getRandomNumber(100) 
    <. 59 
    >  getRandomNumber(1000) 
    <. 431 
    >

    An important observation here is that after the first line curly bracket REPL didn’t evaluate the statement/expression. Instead, it went on the input mode to take more user text. After closing the curly bracket, it stored the function for future evaluation.

    Note: Math.random() returns a random decimal value within the range of 0 to 1.

    Loops in REPL

    We can also execute loops in REPL. As we observed for functions, REPL will wait for the closing curly brace and then evaluates. Let’s take a for loop to demonstrate it.

    > for (var i = 0; i < 100; i++) { 
        var sqrt = Math.sqrt(i); 
        if (Math.floor(sqrt) === Math.ceil(sqrt)) { 
            console.log(i); 
        } 
      } 
      0 
      1 
      4 
      9 
      16 
      25 
      36 
      49 
      64 
      81 
    <. undefined 
    >

    Note that the output is undefined but during execution/evaluation of for-loop we added the console.log to display the numbers which have prefect square roots with integer values.

    Also, REPL didn’t execute the expression after the first closing curly brace as REPL understands it is for the IF statement and not for the FOR loop. So, it tracks the number of open and closed curly brackets.

    REPL in NodeJS

    In node.js terminal, we have a few other options which are listed down and can be obtained by writing ‘.help’ and pressing the ‘ENTER’ key.

    COMMAND
    DESCRIPTION
    .breakSometimes you get stuck, this gets you out
    .clearAlias for .break
    .editorEnter editor mode
    .exitExit the REPL
    .helpPrint this help message
    .loadLoad JS from a file into the REPL session
    .saveSave all evaluated commands in this REPL session to a file

    From the above list, we have already used a few of them like .exit and .help. Let’s look at the other options.

    Overview of REPL commands

    .break - When in the process of inputting a multi-line expression like writing a for loop, enter the .break command (or press Ctrl+C) to abort further input or processing of that expression.

    How to use the Node.js REPL
    .editor - Helps in going to editor mode to process multiple lines, functions, etc. On pressing Ctrl+D, it will execute the code written in editor, and to cancel press Ctrl+C.

    How to use the Node.js REPL

    .Save - Helps to save all the operations done to the file for future reference.

    How to use the Node.js REPL

    .load - helps to load the file into the current REPL session.

    How to use the Node.js REPL

    The REPL Module

    Overview on Standalone REPL Module

    Node.js also comes up with a REPL module that is available as standalone or includible in other applications. All the functionalities we discussed above are available in this module as well. The respective input and output are defaulted to Process.stdin and Process.stdout can be configured to any other Node.js stream.

    Since it is exposed as a module it has access to the internal core modules and load them in REPL environment.

    Exception Handling

    REPL uses the domain module for all uncaught exceptions in their respective session. And the effect of this is that the uncaught exception only emits the ‘uncaughtException’ event and a listener to this event in other node.js results in ERR_INVALID_REPL_INPUT.

    Similarly, if we use process.setUncaughtExceptionCaptureCallback() then it will show an ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE error.

    REPL supports asynchronous functionality

    Await keyword is supported and enabled. Let’s look at an example.

    > async function Sample() { 
    ... console.log(await Promise.resolve('test')); 
    ... } 
    undefined 
    > Sample() 
    Promise { <pending> } 
    > test

    An REPL can be exposed from node.js application with the help of repl module.

    • Create a node js application using npm init.
    • Fill the package details with valid info.
    • Create an index.js file with the below code.
    • Install the repl module using npm I.e., npm install repl.
    • Run node index.js and perform same kind of action as we do on REPL.
    import repl from 'repl'; 
    repl.start({   
    prompt: 'Node.js via stdin:',   
    input: process.stdin,   
    output: process.stdout   
    });

    Output:

    How to use the Node.js REPL

    Customization

    With the help of environment variables, REPL behavior can be customized.

    • NODE_REPL_HISTORY – path where the REPL history will be stored. To disable REPL history set it to empty string '’.
    • NODE_REPL_HISTORY_SIZE – As the name suggests the number of lines of history to be persisted with the default being 1000 and accepts only positive number.
    • NODE_REPL_MODE – allows the code to run in strict or sloppy mode with default being sloppy.

    Sharing REPL instances

    Single/Multiple REPL instances can be created and run in an instance of Node.js which can be shared via global object.

    Unlock the power of Python with our top-rated course! Discover the secrets of this versatile language and become a coding pro. Enroll now for the best Python learning course.

    Usage of REPL module

    The following example provides a REPL instance on stdin of a TCP socket and the same could be created in different Unix socket or same socket with a different port.

    Steps:

    • Open the terminal
    • Create a folder namely REPL using mkdir and navigate inside the folder.
    • Execute npm init
    • Fill the required details on prompt for package.json file, take the default wherever possible with package name customrepl.
    • Create two files Server.js and Client.js file with the below content.
    • Install net and repl module using npm I.e.,
      • npm install net and
      • npm install repl
    • Execute node Server.js file to start the server in same terminal.
    • Invoke another terminal and navigate to REPL folder.
    • Execute node Client.js file to start the client.
    • Now the client has the ability to perform REPL actions on client.

    server.js file:

    import net from 'net'; 
    import repl from 'repl'; 
    net.createServer(function (socket) { 
    var r = repl.start({ 
    prompt: 'Node.js via TCP socket> ' 
    , input: socket 
    , output: socket 
    , terminal: true 
    , useGlobal: false 
    }) 
    r.on('exit', function () { 
    socket.end() 
    }) 
    }).listen(5001);

    client.js file:

    import net from 'net'; 
    var sock = net.connect(5001) 
    process.stdin.pipe(sock) 
    sock.pipe(process.stdout) 
    sock.on('connect', function () { 
    process.stdin.resume(); 
    process.stdin.setRawMode(true) 
    })

    Output:

    How to use the Node.js REPL

    Significance of REPL 

    REPL is an interactive environment that comes with installing node.js, helps to execute JS code without saving or writing to a file. Understanding this is important to anyone who wants to work with Node. Try what you have read here starting from the basic arithmetic operation, expressions to having node.js REPL over net.server.

    Profile

    Sumanth Reddy

    Author

    Full stack,UI Architect having 14+ Years of experience in web, desktop and mobile application development with strong Javascript/.Net programming skills .Strong experience in microsoft tech stack and Certified in OCI associate. Go-to-guy on integration of applications, building a mobile app by zeroing on tech stack. Majorily experienced on engineering based IIOT products and Marekting Automation products deployed on premise and on-cloud. 

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon