事件:'reset'


【Event: 'reset'

'reset' 事件在 REPL 的上下文重置时触发。每当接收到 .clear 命令作为输入时都会发生这种情况,除非 REPL 使用的是默认求值器,并且 repl.REPLServer 实例是通过将 useGlobal 选项设置为 true 创建的。监听器回调将会使用 context 对象的引用作为唯一参数被调用。

【The 'reset' event is emitted when the REPL's context is reset. This occurs whenever the .clear command is received as input unless the REPL is using the default evaluator and the repl.REPLServer instance was created with the useGlobal option set to true. The listener callback will be called with a reference to the context object as the only argument.】

这主要可以用于将 REPL 上下文重新初始化到某个预定义状态:

【This can be used primarily to re-initialize REPL context to some pre-defined state:】

import repl from 'node:repl';

function initializeContext(context) {
  context.m = 'test';
}

const r = repl.start({ prompt: '> ' });
initializeContext(r.context);

r.on('reset', initializeContext);const repl = require('node:repl');

function initializeContext(context) {
  context.m = 'test';
}

const r = repl.start({ prompt: '> ' });
initializeContext(r.context);

r.on('reset', initializeContext);

当执行此代码时,全局变量 'm' 可以被修改,但随后可以使用 .clear 命令将其重置为初始值:

【When this code is executed, the global 'm' variable can be modified but then reset to its initial value using the .clear command:】

$ ./node example.js
> m
'test'
> m = 1
1
> m
1
> .clear
Clearing context...
> m
'test'
>