鍍金池/ 問答/Linux  HTML/ nodejs命令行,子進(jìn)程我是用了colors打印,父進(jìn)程如何得到。

nodejs命令行,子進(jìn)程我是用了colors打印,父進(jìn)程如何得到。

nodejs命令行,子進(jìn)程我是用了colors打印,父進(jìn)程如何得到。

子進(jìn)程aaa.js

require("colors")
console.log("aaa".red)

父進(jìn)程run.js

require('child_process').exec("node aaa",{ stdio: "inherit"},function (err,out) {
  console.log(out)
})

如何能帶顏色啊。

回答
編輯回答
膽怯

你可以使用下面代碼實(shí)現(xiàn)你需要的效果:

require('child_process').spawn('node', ['aaa'], { stdio: 'inherit' })

但是如果你需要細(xì)致的理解,首先要知道終端是怎么控制輸出的顏色的。
轉(zhuǎn)義序列(1)是終端用來控制顏色的特殊字符序列的,這部分的
由于是控制字符序列,所以他們是不可見的,
轉(zhuǎn)義序列由 ESC(2)[ 開始,然后緊跟著parameter bytes,范圍在0x30–0x3F,再后面是intermediate bytes,范圍在0x20–0x2F,最后跟著final byte,范圍在0x40–0x7E。

看下面的代碼就更能理解了:

require("colors")

// 31 in 30–37    Set foreground color
// 39           Default foreground color
var redStringUnicode = '\u001b[31maaa\u001b[39m'
var redStringAscii = '\033[31maaa\033[39m'
var redStr = "aaa".red
console.log('unicode?:', redStringUnicode)
console.log('unicode length:', redStringUnicode.length)  // 13
console.log('ascii escape:', redStringAscii)
console.log('ascii escape length:', redStringAscii.length)  // 13
console.log('colors:', redStr)
console.log('colors length:', redStr.length) // 13
console.log(redStr === redStringAscii) // true
console.log(redStr === redStringUnicode) // true
console.log(redStringAscii === redStringUnicode) // true

其中,之所以經(jīng)過父子進(jìn)程通信之后,顏色就不顯示了,是因?yàn)?colors 庫中有個(gè) supports-colors.js 邏輯來判斷是否支持顏色,其中有一句:

if (process.stdout && !process.stdout.isTTY) {
    return false;
}

而使用 exec 方法執(zhí)行命令,則子進(jìn)程的 stdio 就與 tty(終端)失去了聯(lián)系,也就是 process.stdout.isTTY === 'undefined',只要保證 `process.stdout 對應(yīng)為終端輸出流即可

注解

  • (1) 其實(shí)轉(zhuǎn)義序列分為多種,這里指的只是 CSI - Control Sequence Introducer 一類
  • (2) ESC 的Ascii碼為27,Unicode碼為U+001B
2018年6月17日 10:36