我有一个 NodeJS 应用程序需要使用 执行一些命令spawn,我正在读取输出以供以后处理,使用readline它可以完美地工作。
但我还需要获取文本的颜色,例如:在执行另一个Node.js使用chalkmodule.txt 的脚本时。
如何才能做到这一点?
到目前为止,这是我的代码:
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 ..
});
Run Code Online (Sandbox Code Playgroud)
Amr K. Aly 的答案确实有效,但在执行外部NodeJS脚本时它返回空颜色。
我的代码(index.js):
const spawn = …Run Code Online (Sandbox Code Playgroud)