REPL evaluate `.scope` when it needs to get a list of the variable names available in the current scope. Do not throw if the output of such evaluation is not array, just ignore it. PR-URL: https://github.com/nodejs/io.js/pull/1682 Reviewed-By: Fedor Indutny <fedor@indutny.com>
8.0 KiB
REPL
Stability: 2 - Stable
A Read-Eval-Print-Loop (REPL) is available both as a standalone program and easily includable in other programs. The REPL provides a way to interactively run JavaScript and see the results. It can be used for debugging, testing, or just trying things out.
By executing iojs
without any arguments from the command-line you will be
dropped into the REPL. It has simplistic emacs line-editing.
mjr:~$ iojs
Type '.help' for options.
> a = [ 1, 2, 3];
[ 1, 2, 3 ]
> a.forEach(function (v) {
... console.log(v);
... });
1
2
3
For advanced line-editors, start io.js with the environmental variable
NODE_NO_READLINE=1
. This will start the main and debugger REPL in canonical
terminal settings which will allow you to use with rlwrap
.
For example, you could add this to your bashrc file:
alias iojs="env NODE_NO_READLINE=1 rlwrap iojs"
The built-in repl (invoked by running iojs
or iojs -i
) may be controlled
via the following environment variables:
NODE_REPL_HISTORY_FILE
- if given, must be a path to a user-writable, user-readable file. When a valid path is given, persistent history support is enabled: REPL history will persist acrossiojs
repl sessions.NODE_REPL_HISTORY_SIZE
- defaults to1000
. In conjunction withNODE_REPL_HISTORY_FILE
, controls how many lines of history will be persisted. Must be a positive number.NODE_REPL_MODE
- may be any ofsloppy
,strict
, ormagic
. Defaults tomagic
, which will automatically run "strict mode only" statements in strict mode.
repl.start(options)
Returns and starts a REPLServer
instance, that inherits from
[Readline Interface][]. Accepts an "options" Object that takes
the following values:
-
prompt
- the prompt andstream
for all I/O. Defaults to>
. -
input
- the readable stream to listen to. Defaults toprocess.stdin
. -
output
- the writable stream to write readline data to. Defaults toprocess.stdout
. -
terminal
- passtrue
if thestream
should be treated like a TTY, and have ANSI/VT100 escape codes written to it. Defaults to checkingisTTY
on theoutput
stream upon instantiation. -
eval
- function that will be used to eval each given line. Defaults to an async wrapper foreval()
. See below for an example of a customeval
. -
useColors
- a boolean which specifies whether or not thewriter
function should output colors. If a differentwriter
function is set then this does nothing. Defaults to the repl'sterminal
value. -
useGlobal
- if set totrue
, then the repl will use theglobal
object, instead of running scripts in a separate context. Defaults tofalse
. -
ignoreUndefined
- if set totrue
, then the repl will not output the return value of command if it'sundefined
. Defaults tofalse
. -
writer
- the function to invoke for each command that gets evaluated which returns the formatting (including coloring) to display. Defaults toutil.inspect
. -
replMode
- controls whether the repl runs all commands in strict mode, default mode, or a hybrid mode ("magic" mode.) Acceptable values are:
repl.REPL_MODE_SLOPPY
- run commands in sloppy mode.repl.REPL_MODE_STRICT
- run commands in strict mode. This is equivalent to prefacing every repl statement with'use strict'
.repl.REPL_MODE_MAGIC
- attempt to run commands in default mode. If they fail to parse, re-try in strict mode.
You can use your own eval
function if it has following signature:
function eval(cmd, context, filename, callback) {
callback(null, result);
}
On tab completion - eval
will be called with .scope
as an input string. It
is expected to return an array of scope names to be used for the auto-completion.
Multiple REPLs may be started against the same running instance of io.js. Each will share the same global object but will have unique I/O.
Here is an example that starts a REPL on stdin, a Unix socket, and a TCP socket:
var net = require("net"),
repl = require("repl");
connections = 0;
repl.start({
prompt: "io.js via stdin> ",
input: process.stdin,
output: process.stdout
});
net.createServer(function (socket) {
connections += 1;
repl.start({
prompt: "io.js via Unix socket> ",
input: socket,
output: socket
}).on('exit', function() {
socket.end();
})
}).listen("/tmp/iojs-repl-sock");
net.createServer(function (socket) {
connections += 1;
repl.start({
prompt: "io.js via TCP socket> ",
input: socket,
output: socket
}).on('exit', function() {
socket.end();
});
}).listen(5001);
Running this program from the command line will start a REPL on stdin. Other
REPL clients may connect through the Unix socket or TCP socket. telnet
is useful
for connecting to TCP sockets, and socat
can be used to connect to both Unix and
TCP sockets.
By starting a REPL from a Unix socket-based server instead of stdin, you can connect to a long-running io.js process without restarting it.
For an example of running a "full-featured" (terminal
) REPL over
a net.Server
and net.Socket
instance, see: https://gist.github.com/2209310
For an example of running a REPL instance over curl(1)
,
see: https://gist.github.com/2053342
Event: 'exit'
function () {}
Emitted when the user exits the REPL in any of the defined ways. Namely, typing
.exit
at the repl, pressing Ctrl+C twice to signal SIGINT, or pressing Ctrl+D
to signal "end" on the input
stream.
Example of listening for exit
:
r.on('exit', function () {
console.log('Got "exit" event from repl!');
process.exit();
});
Event: 'reset'
function (context) {}
Emitted when the REPL's context is reset. This happens when you type .clear
.
If you start the repl with { useGlobal: true }
then this event will never
be emitted.
Example of listening for reset
:
// Extend the initial repl context.
r = repl.start({ options ... });
someExtension.extend(r.context);
// When a new context is created extend it as well.
r.on('reset', function (context) {
console.log('repl has a new context');
someExtension.extend(context);
});
REPL Features
Inside the REPL, Control+D will exit. Multi-line expressions can be input. Tab completion is supported for both global and local variables.
Core modules will be loaded on-demand into the environment. For example,
accessing fs
will require()
the fs
module as global.fs
.
The special variable _
(underscore) contains the result of the last expression.
> [ "a", "b", "c" ]
[ 'a', 'b', 'c' ]
> _.length
3
> _ += 1
4
The REPL provides access to any variables in the global scope. You can expose
a variable to the REPL explicitly by assigning it to the context
object
associated with each REPLServer
. For example:
// repl_test.js
var repl = require("repl"),
msg = "message";
repl.start("> ").context.m = msg;
Things in the context
object appear as local within the REPL:
mjr:~$ iojs repl_test.js
> m
'message'
There are a few special REPL commands:
.break
- While inputting a multi-line expression, sometimes you get lost or just don't care about completing it..break
will start over..clear
- Resets thecontext
object to an empty object and clears any multi-line expression..exit
- Close the I/O stream, which will cause the REPL to exit..help
- Show this list of special commands..save
- Save the current REPL session to a file.save ./file/to/save.js
.load
- Load a file into the current REPL session..load ./file/to/load.js
The following key combinations in the REPL have these special effects:
<ctrl>C
- Similar to the.break
keyword. Terminates the current command. Press twice on a blank line to forcibly exit.<ctrl>D
- Similar to the.exit
keyword.<tab>
- Show both global and local(scope) variables