在同一进程中启动多个 REPL 实例
¥Starting multiple REPL instances in the same process
可以针对单个正在运行的 Node.js 实例创建并运行多个 REPL 实例,这些实例共享一个 global
对象(通过将 useGlobal
选项设置为 true
),但具有单独的 I/O 接口。
¥It is possible to create and run multiple REPL instances against a single
running instance of Node.js that share a single global
object (by setting
the useGlobal
option to true
) but have separate I/O interfaces.
例如,以下示例在 stdin
、Unix 套接字和 TCP 套接字上提供了单独的 REPL,它们共享同一个 global
对象:
¥The following example, for instance, provides separate REPLs on stdin
, a Unix
socket, and a TCP socket, all sharing the same global
object:
import net from 'node:net';
import repl from 'node:repl';
import process from 'node:process';
import fs from 'node:fs';
let connections = 0;
repl.start({
prompt: 'Node.js via stdin> ',
useGlobal: true,
input: process.stdin,
output: process.stdout,
});
const unixSocketPath = '/tmp/node-repl-sock';
// If the socket file already exists let's remove it
fs.rmSync(unixSocketPath, { force: true });
net.createServer((socket) => {
connections += 1;
repl.start({
prompt: 'Node.js via Unix socket> ',
useGlobal: true,
input: socket,
output: socket,
}).on('exit', () => {
socket.end();
});
}).listen(unixSocketPath);
net.createServer((socket) => {
connections += 1;
repl.start({
prompt: 'Node.js via TCP socket> ',
useGlobal: true,
input: socket,
output: socket,
}).on('exit', () => {
socket.end();
});
}).listen(5001);
const net = require('node:net');
const repl = require('node:repl');
const fs = require('node:fs');
let connections = 0;
repl.start({
prompt: 'Node.js via stdin> ',
useGlobal: true,
input: process.stdin,
output: process.stdout,
});
const unixSocketPath = '/tmp/node-repl-sock';
// If the socket file already exists let's remove it
fs.rmSync(unixSocketPath, { force: true });
net.createServer((socket) => {
connections += 1;
repl.start({
prompt: 'Node.js via Unix socket> ',
useGlobal: true,
input: socket,
output: socket,
}).on('exit', () => {
socket.end();
});
}).listen(unixSocketPath);
net.createServer((socket) => {
connections += 1;
repl.start({
prompt: 'Node.js via TCP socket> ',
useGlobal: true,
input: socket,
output: socket,
}).on('exit', () => {
socket.end();
});
}).listen(5001);
从命令行运行此应用将在标准输入上启动 REPL。其他 REPL 客户端可以通过 Unix 套接字或 TCP 套接字连接。例如,telnet
可用于连接 TCP 套接字,而 socat
可用于连接 Unix 和 TCP 套接字。
¥Running this application from the command line will start a REPL on stdin.
Other REPL clients may connect through the Unix socket or TCP socket. telnet
,
for instance, is useful for connecting to TCP sockets, while socat
can be used
to connect to both Unix and TCP sockets.
通过从基于 Unix 套接字的服务器而不是标准输入启动 REPL,可以连接到长时间运行的 Node.js 进程而无需重新启动它。
¥By starting a REPL from a Unix socket-based server instead of stdin, it is possible to connect to a long-running Node.js process without restarting it.