自定义 REPL 输出
默认情况下,repl.REPLServer
实例在将输出写入提供的 Writable
流(默认为 process.stdout
)之前使用 util.inspect()
方法格式化输出。
showProxy
检查选项默认设置为 true,colors
选项设置为 true,具体取决于 REPL 的 useColors
选项。
可以在构造时指定 useColors
布尔选项,以指示默认编写器使用 ANSI 风格的代码为 util.inspect()
方法的输出着色。
如果 REPL 作为独立程序运行,也可以通过使用 inspect.replDefaults
属性(反映了 util.inspect()
中的 defaultOptions
)从 REPL 内部更改 REPL 的检查默认值。
> util.inspect.replDefaults.compact = false;
false
> [1]
[
1
]
>
要完全自定义 repl.REPLServer
实例的输出,则在构建时为 writer
选项传入新函数。
例如,下面的示例只是将任何输入文本转换为大写:
const repl = require('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();
}
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.
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.
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
]
>
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:
const repl = require('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();
}