我正在尝试将控制台输出中的 ansi 颜色代码转换为 HTML。我找到了一个脚本来执行此操作,但我似乎无法让它解析 Node js 内的字符串。我尝试对其进行 JSON.stringify 以包含特殊字符,但它不起作用。
forever list
[32minfo[39m: Forever processes running
[90mscript[39m [37mforever[39m [37mpid[39m [37mid[39m
[90mdata[39m: [37m [39m [37muid[39m [90mcommand[39m
我从 Node js 中的 ssh2shell 得到这样的输出。我有一个脚本: https://github.com/pixelb/scripts/blob/master/scripts/ansi2html.sh
这应该将上面的内容转换为 html 并添加适当的颜色代码。它可以很好地处理正常的终端输出,例如:
npm install --color=always | ansi2html.sh > npminstall.html
这是 Linux 机器上通过管道传输到文件的原始输出。 JS 字符串在 console.log 中显示时似乎缺少这些转义符,但也缺少换行符。也许是因为我将它们直接连接到字符串中并删除了特殊字符?
total 24
-rwxr-xr-x 1 admin admin 17002 May 13 02:52 ^[[0m^[[38;5;34mansi2html.sh^[[0m
drwxr-xr-x 4 admin admin 4096 May 13 00:00 ^[[38;5;27mgit^[[0m
-rw-r--r-- 1 admin admin 0 May 13 02:57 ls.html
希望其中一些是有意义的。
谢谢
最佳答案
SSH2shell 对命令的输出应用了几个过滤器。第一个从响应中删除非标准 ASCII,然后删除颜色格式代码。
在 v1.6.0 中,我添加了 pipeline()/unpipe() 事件,并公开了stream.on('data', function(data){}) 事件,以便您可以直接访问流输出,而无需SSH2shell 以任何方式与其交互。 这应该可以通过让您访问原始数据来解决无法从 SSH2shell 获得正确输出的问题。
var fs = require('fs')
var host = {
server: {
host: mydomain.com,
port: 22,
userName: user,
password: password:)
},
commands: [
"`Test session text message: passed`",
"msg:console test notification: passed",
"ls -la"
],
}
//until npm published use the cloned dir path.
var SSH2Shell = require ('ssh2shell')
//run the commands in the shell session
var SSH = new SSH2Shell(host),
callback = function( sessionText ){
console.log ( "-----Callback session text:\n" + sessionText);
console.log ( "-----Callback end" );
},
firstLog = fs.createWriteStream('first.log'),
secondLog = fs.createWriteStream('second.log'),
buffer = ""
//multiple pipes can be added but they wont be bound to the stream until the connection is established
SSH.pipe(firstLog).pipe(secondLog);
SSH.on('data', function(data){
//do something with the data chunk
console.log(data)
})
SSH.connect(callback)
关于javascript - 字符串解析不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37200653/