Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Node.js REPL


May 10, 2021 Node.js


Table of contents


Repl

REPL, the interactive interpreter that Node brings with it, can do the following:

  • Read - You can read the user's input, parse the input Javascript data structure, and store it in memory.
  • Execution (Eval) - The Javascript data structure that can be entered.
  • Print - Print out.
  • Loop - Cycle the steps above, and if exit is required, the user will need to press the ctrl-c button twice.
稳定性: 3 - 稳定

Read-Eval-Print-Loop (REPL Read-Execute-Output Loop) can be used as a stand-alone program or integrated into other programs.

REPL provides an interactive way to execute JavaScript and view the output. Can be used for debugging, testing, or just for testing.

Execution node without any parameters on the command node is the REPL mode. It provides simple emacs line editing.

mjr:~$ node
Type '.help' for options.
> a = [ 1, 2, 3];
[ 1, 2, 3 ]
> a.forEach(function (v) {
...   console.log(v);
...   });
1
2
3

To use the advanced editing mode, open node NODE_NO_READLINE=1 This turns on REPL mode and allows you to rlwrap

For example, you can add the following code to your bashrc file.

alias node="env NODE_NO_READLINE=1 rlwrap node"

repl.start(options)

Start and return an REPLServer instance. I t inherits from the "Readline Interface" . The received parameter "options" has the following values:

  • prompt - prompts and streams for all inputs and outputs, by default > .

  • input - A readable stream that needs to be monitored, which process.stdin .

  • output - A writeable stream used to output data, which process.stdout .

  • terminal - If stream is treated as TTY and has ANSI/VT100 escape, transmit true Check isTTY on the output stream of the instance by default.

  • eval - A function used to value each row. T he eval() See the custom eval

  • useColors - Writes whether the function output has color. I f a different writer function writer it is not valid. The terminal value of repl terminal

  • useGlobal - If true repl will use the global object instead of running scripts in a separate context. T he default is false

  • ignoreUndefined If true, true does not output the return value of an undefined command. T he default is false

  • writer - This function is called when each command line is valued, and it returns the formatted display, including color. The default is util.inspect

You can use your own eval function eval

function eval(cmd, context, filename, callback) {
  callback(null, result);
}

Multiple REPLs can be opened on the same node running instance. Each shared a global object, but there will be a separate I/O.

For the following example, turn on REPL on stdin, Unix socket, and TCP socket:

var net = require("net"),
    repl = require("repl");

connections = 0;

repl.start({
  prompt: "node via stdin> ",
  input: process.stdin,
  output: process.stdout
});

net.createServer(function (socket) {
  connections += 1;
  repl.start({
    prompt: "node via Unix socket> ",
    input: socket,
    output: socket
  }).on('exit', function() {
    socket.end();
  })
}).listen("/tmp/node-repl-sock");

net.createServer(function (socket) {
  connections += 1;
  repl.start({
    prompt: "node via TCP socket> ",
    input: socket,
    output: socket
  }).on('exit', function() {
    socket.end();
  });
}).listen(5001);

Running this program from the command line will start REPL on stdin. O ther REPL clients may be connected via Unix socket or TCP socket. telnet commonly used to connect TCP sockets, socat are used to connect Unix and TCP sockets

Start REPL from the Unix socket-base server instead of stdin, and you can establish long connections without restarting them.

Through net.Server and net.Socket instance runs an example of a terminal see: https://gist.github.com/2209310

For curl(1) instance, see: https://gist.github.com/2053342

Event: 'exit'

function () {}

This event is triggered when the user exits THEPL in a predefined manner. Predefined methods include .exit in the repl, sending the SIGINT signal twice by Ctrl-C, input by pressing Ctrl-D on the input stream.

An example of exit

r.on('exit', function () {
  console.log('Got "exit" event from repl!');
  process.exit();
});

Event: 'reset'

function (context) {}

Triggered when resetting the context of the REPL. W hen you enter .clear resets. This event { useGlobal: true } start the reppl with the word Global: true .

Examples of 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

In THEPL, Control-D exits. Y ou can enter multiple lines of expressions. TAB auto-complements that support global and local variables.

The special _ , (underscore), contains the result of the last expression.

> [ "a", "b", "c" ]
[ 'a', 'b', 'c' ]
> _.length
3
> _ += 1
4

REPL supports access to any variable in the global domain. By assigning variables to REPLServer you can display the speaking variables exposed to REPLS, for example:

// repl_test.js
var repl = require("repl"),
    msg = "message";

repl.start("> ").context.m = msg;

context in the context object appears as a local variable:

mjr:~$ node repl_test.js
> m
'message'

There are some special REPL commands:

  • .break - When you enter a multi-line expression, perhaps you're out of your way or don't want to finish it, .break can start over.
  • .clear - context object to empty the object and emptys the multi-line expression.
  • .exit - Turn off the input/output stream, which will cause the REPL to exit.
  • .help - Print these special commands.
  • .save - Save the current REPL session to the file.

    .save ./file/to/save.js

  • .load - Load a file into the current REPL session

    .load ./file/to/load.js

The following key combinations have the following effects in REPL:

  • <ctrl>C .break key, pressing twice on an empty line forces an exit.
  • <ctrl>D - is similar .exit key.