Soorya Prakash
Soorya Prakash

Reputation: 991

Use of REPL in node js

  1. What is the use of REPL in nodejs?
  2. What are the use-cases/scenario for using REPL?
  3. When should I use the REPL node module in nodejs?

I have understood the API Doc, how to include REPL module and how to start the REPL instance using the prompt and eval.

But can anyone help me to understood above question? So that I can understand how exactly the REPL module can be used?

Upvotes: 6

Views: 1366

Answers (1)

Niklas Higi
Niklas Higi

Reputation: 2309

What are the use-cases/scenario for using REPL?

I've often seen it (or Chrome's console which is a JavaScript REPL as well) used in tech talks as a quick way to demonstrate what different expressions evaluate to. Let's image you're holding a talk about Equality in JavaScript and want to show that NaN strangely is not equal to itself.

You could demonstrate that by:

  • running node without arguments in your terminal (this starts the REPL)
  • entering NaN == NaN and pressing Enter (the REPL will evaluate the expression)
  • pretending to be surprised that the output is false

When should I use the REPL node module in nodejs?

When you want to implement a Node.js REPL as part of your application, for example by exposing it through a "remote terminal" in a web browser (not recommending that because of security reasons).

Examples

Replicating the REPL that is shown by calling node

const repl = require('repl')
const server = repl.start()

Using the REPLServer's stream API

fs-repl.js file:

const repl = require('repl')
const fs = require('fs')
const { Readable } = require('stream')

const input = new fs.createReadStream('./input.js')

const server = repl.start({
  input,
  output: process.stdout
})

input.js file:

40 + 2
NaN
["hello", "world"].join(" ")

You can now run node fs-repl and you will get the following output:

> 40 + 2
42
> NaN
NaN
> ["hello", "world"].join(" ")
'hello world'

This output can obviously be passed into a Writable stream other than process.stdout by changing the output option.

Upvotes: 6

Related Questions