![](/img/trans.png)
[英]How to get synchronous readline, or "simulate" it using async, in nodejs?
[英]NodeJS get color in readline
我有一个 NodeJS 应用程序需要使用spawn
执行一些命令,我正在使用readline
读取输出以供以后处理,它可以完美地工作。
但我还需要获取文本的颜色,例如:执行另一个使用chalk
模块的Node.js
脚本时。
如何做到这一点?
到目前为止,这是我的代码:
const spawn = require('child_process').spawn;
const readline = require('readline');
let myCommand = spawn(<command>, [<args...>], { cwd: dirPath });
readline.createInterface({
input : myCommand.stdout,
terminal : true
}).on('line', (line) => handleOutput(myCommand.pid, line));
readline.createInterface({
input : myCommand.stderr,
terminal : true
}).on('line', (line) => handleErrorOutput(myCommand.pid, line));
myCommand.on('exit', (code) => {
// Do more stuff ..
});
Amr K. Aly 的答案确实有效,但在执行外部NodeJS
脚本时,它返回空颜色。
我的代码(index.js) :
const spawn = require('child_process').spawn;
const readline = require('readline');
let myCommand = spawn('node', ['cmd.js']);
readline.createInterface({
input: myCommand.stdout,
terminal: true
}).on('line', (line) => handleOutput(myCommand.pid, line));
readline.createInterface({
input: myCommand.stderr,
terminal: true
}).on('line', (line) => handleErrorOutput(myCommand.pid, line));
myCommand.on('exit', (code) => {
// Do more stuff ..
});
function handleErrorOutput(obj, obj2) {}
function handleOutput(obj, line, a, b, c) {
//PRINT TEXT WITH ANSI FORMATING
console.log(line);
//REGEX PATTERN TO EXTRACT COLOR
var options = Object.assign({
onlyFirst: false
});
const pattern = [
'[\\u001B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
'(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'
].join('|');
var regex = new RegExp(pattern, options.onlyFirst ? undefined : 'g');
var ansiColor = (line.match(regex));
//PRINT EXTRACTED ANSI
console.log("ANSI COLOR CODE :");
console.log(ansiColor);
}
cmd.js :
const chalk = require('chalk');
console.log(chalk.blue('Blue Hello world!'));
console.log(chalk.green('green Hello world!'));
console.log(chalk.red('red Hello world!'));
我的结果:
问题:
打印回您阅读的文本流时您看不到颜色,因为您已将 createInterface 中的terminal
选项设置为true
。 这会导致 createInterface() 不返回 ANSI/VT100 编码。
解决方案:
terminal
选项需要设置为false
以便文本将使用 ANSI/VT100 编码来自 Nodejs Docs: terminal <boolean> true if the input and output streams should be treated like a TTY, and have ANSI/VT100 escape codes written to it. Default: checking isTTY on the output stream upon instantiation.
terminal <boolean> true if the input and output streams should be treated like a TTY, and have ANSI/VT100 escape codes written to it. Default: checking isTTY on the output stream upon instantiation.
请参阅readline.createInterface(options) 文档
readline.createInterface({
input: myCommand.stdout,
terminal: true//<== NEEDS TO BE SET TO FALSE
}).on('line', (line) => handleOutput(myCommand.pid, line));
将terminal
设置为false
,返回的文本将采用 ANSI/VT100 编码。 然后,您需要提取与颜色相关的 ANSI/VT100 编码,并将其更改为您需要的任何颜色格式。
请参阅下面的修改后的代码和输出,并添加了正则表达式以提取 ANSI 颜色代码。 您需要添加自己的逻辑来处理 ANSI 转义颜色。
const spawn = require('child_process').spawn;
const readline = require('readline');
const chalk = require('chalk');
//Testing on windows 10
let myCommand = spawn(process.env.comspec, ['/c', 'echo ' + chalk.red('Hello world!'), ], {
// cwd: dirPath
});
readline.createInterface({
input: myCommand.stdout,
terminal: false
}).on('line', (line) => handleOutput(myCommand.pid, line));
readline.createInterface({
input: myCommand.stderr,
terminal: false
}).on('line', (line) => handleErrorOutput(myCommand.pid, line));
myCommand.on('exit', (code) => {
// Do more stuff ..
});
function handleErrorOutput(obj, obj2) {}
function handleOutput(obj, line) {
//PRINT TEXT WITH ANSI FORMATING
console.log(line);
//REGEX PATTERN TO EXTRACT COLOR
var options = Object.assign({
onlyFirst: false
});
const pattern = [
'[\\u001B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
'(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'
].join('|');
var regex = new RegExp(pattern, options.onlyFirst ? undefined : 'g');
var ansiColor = (line.match(regex));
//PRINT EXTRACTED ANSI
console.log("ANSI COLOR CODE :");
console.log(ansiColor);
}
上面代码的输出:
编辑:
Chalk 会自动检测您是否正在写入 TTY 或终端不支持颜色并禁用着色。 您可以通过设置环境变量FORCE_COLOR=1
或通过传递--color
作为参数来强制它。
如果您将代码更改为以下代码段中的行,Chalk 应该正确添加样式。
let myCommand = spawn('node', ['test.js', '--color', ], {
});
输出:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.