Tuesday, December 22, 2020

Node.js Console - REPL

Node.js comes with virtual environment called REPL (aka Node shell). REPL stands for Read-Eval-Print-Loop. It is a quick and easy way to test simple Node.js/JavaScript code.

To launch the REPL (Node shell), open command prompt (in Windows) or terminal (in Mac or UNIX/Linux) and type node as shown below. It will change the prompt to > in Windows and MAC.

Launch Node.js REPL

You can now test pretty much any Node.js/JavaScript expression in REPL. For example, if your write "10 + 20" then it will display result 30 immediately in new line.

> 10 + 20
30

The + operator also concatenates strings as in browser's JavaScript.

> "Hello " + "World"
Hello World

You can also define variables and perform some operation on them.

> var x = 10, y = 20;
> x + y
30

If you need to write multi line JavaScript expression or function then just press Enter whenever you want to write something in the next line as a continuation of your code. The REPL terminal will display three dots (...), it means you can continue on next line. Write .break to get out of continuity mode.

For example, you can define a function and execute it as shown below.

Node.js Example in REPL

You can execute an external JavaScript file by writing node fileName command. For example, assume that node-example.js is on C drive of your PC with following code.

node-example.js
console.log("Hello World");

Now, you can execute node-exampel.js from command prompt as shown below.

Run External JavaScript file

To exit from the REPL terminal, press Ctrl + C twice or write .exit and press Enter.

Quit from REPL

Thus, you can execute any Node.js/JavaScript code in the node shell (REPL). This will give you a result which is similar to the one you will get in the console of Google Chrome browser.

 Note:
ECMAScript implementation in Node.js and browsers is slightly different. For example, {}+{} is '[object Object][object Object]' in Node.js REPL, whereas the same code is NaN in the Chrome console because of the automatic semicolon insertion feature. However, mostly Node.js REPL and the Chrome/Firefox consoles are similar.

The following table lists important REPL commands.

REPL CommandDescription
.helpDisplay help on all the commands
tab KeysDisplay the list of all commands.
Up/Down KeysSee previous commands applied in REPL.
.save filenameSave current Node REPL session to a file.
.load filenameLoad the specified file in the current Node REPL session.
ctrl + cTerminate the current command.
ctrl + c (twice)Exit from the REPL.
ctrl + dExit from the REPL.
.breakExit from multiline expression.
.clearExit from multiline expression.

No comments:

Post a Comment

Kafka setup in window

Here's a step-by-step guide on how to do it : 1. Prerequisites : Before you begin, make sure you have the following prerequisites inst...