自定义 REPL 输出


【Customizing REPL output】

默认情况下,repl.REPLServer 实例在将输出写入提供的 Writable 流(默认是 process.stdout)之前,会使用 util.inspect() 方法格式化输出。showProxy 检查选项默认设置为 true,而 colors 选项则根据 REPL 的 useColors 选项设置为 true。

【By default, repl.REPLServer instances format output using the util.inspect() method before writing the output to the provided Writable stream (process.stdout by default). The showProxy inspection option is set to true by default and the colors option is set to true depending on the REPL's useColors option.】

useColors 布尔选项可以在构造时指定,用于指示默认的写入器使用 ANSI 样式代码为 util.inspect() 方法的输出添加颜色。

【The useColors boolean option can be specified at construction to instruct the default writer to use ANSI style codes to colorize the output from the util.inspect() method.】

如果 REPL 作为独立程序运行,也可以通过在 REPL 内使用 inspect.replDefaults 属性来更改 REPL 的 检查默认值,该属性反映了来自 util.inspect()defaultOptions

【If the REPL is run as standalone program, it is also possible to change the REPL's inspection defaults from inside the REPL by using the inspect.replDefaults property which mirrors the defaultOptions from util.inspect().】

> util.inspect.replDefaults.compact = false;
false
> [1]
[
  1
]
> 

要完全自定义 repl.REPLServer 实例的输出,可以在构造时为 writer 选项传入一个新函数。例如,下面的示例只是将任何输入文本转换为大写字母:

【To fully customize the output of a repl.REPLServer instance pass in a new function for the writer option on construction. The following example, for instance, simply converts any input text to upper case:】

import repl from 'node:repl';

const r = repl.start({ prompt: '> ', eval: myEval, writer: myWriter });

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

function myWriter(output) {
  return output.toUpperCase();
}const repl = require('node:repl');

const r = repl.start({ prompt: '> ', eval: myEval, writer: myWriter });

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

function myWriter(output) {
  return output.toUpperCase();
}