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
nodewithout arguments in your terminal (this starts the REPL) - entering
NaN == NaNand 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.
Videos
There is still nothing built-in to provide the exact functionality you describe. However, an alternative to using require it to use the .load command within the REPL, like such:
.load foo.js
It loads the file in line by line just as if you had typed it in the REPL. Unlike require this pollutes the REPL history with the commands you loaded. However, it has the advantage of being repeatable because it is not cached like require.
Which is better for you will depend on your use case.
Edit: It has limited applicability because it does not work in strict mode, but three years later I have learned that if your script does not have 'use strict', you can use eval to load your script without polluting the REPL history:
var fs = require('fs');
eval(fs.readFileSync('foo.js').toString())
i always use this command
node -i -e "$(< yourScript.js)"
works exactly as in Python without any packages.