Es posible crear un bucle REPL en cualquier punto de nuestro programa - quizá para depurarlo.
Para ello usamos la función
repl.start .
Esta función retorna una instancia REPLServer. Acepta como argumento un objeto
options
que toma los siguientes valores:
prompt
- the prompt and stream for all I/O. Defaults to > .
input
- the readable stream to listen to. Defaults to process.stdin.
output
- the writable stream to write readline data to. Defaults to process.stdout.
terminal
- pass true if the stream should be treated
like a TTY, and have ANSI/VT100 escape codes written to it. Defaults
to checking isTTY on the output stream upon instantiation.
eval
- function that will be used to eval each given
line. Defaults to an async wrapper for eval().
useColors
- a boolean which specifies whether or not
the writer function should output colors. If a different writer
function is set then this does nothing. Defaults to the repl's
terminal value.
useGlobal
- if set to true, then the repl will use the
global object, instead of running scripts in a separate context.
Defaults to false.
ignoreUndefined
- if set to true, then the repl will
not output the return value of command if it's undefined. Defaults
to false.
writer
- the function to invoke for each command that
gets evaluated which returns the formatting (including coloring)
to display. Defaults to util.inspect.
[~/Dropbox/src/javascript/node.js/repl(master)]$ cat repl.js var repl = require("repl"); connections = 0; repl.start({ prompt: "node via stdin> ", input: process.stdin, output: process.stdout });
[~/Dropbox/src/javascript/node.js/repl(master)]$ node repl.js node via stdin> 2+3 5 node via stdin> .exit
el bucle REPL proporciona acceso a las variables de ámbito global. Es posible
hacer explícitamente visible una variable al REPL asignándosela al
context
asociado con el
REPLServer. Por ejemplo:
[~/Dropbox/src/javascript/node.js/repl(master)]$ cat repl2.js var repl = require("repl"); z = 4 repl.start({ prompt: "node via stdin> ", input: process.stdin, output: process.stdout }).context.m = "message";Las variables en el objeto
context
se ven como locales
al REPL:
[~/Dropbox/src/javascript/node.js/repl(master)]$ node repl2.js node via stdin> z 4 node via stdin> m 'message'
Casiano Rodríguez León