2016-05-13 129 views
1

我想將控制檯輸出的ansi色碼轉換爲HTML。我有一個腳本來做到這一點,但我似乎無法讓它解析節點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         

我從節點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 

希望這其中的一些是有道理的。

謝謝

+0

從哪裏得到ANSI字符串?一份文件?標準輸入?在代碼中進行硬編碼? – slebetman

回答

0

試過嗎?

https://github.com/hughsk/ansi-html-stream

var spawn = require('child_process').spawn 
    , ansi = require('ansi-html-stream') 
    , fs = require('fs') 

var npm = spawn('npm', ['install', 'browserify', '--color', 'always'], { 
    cwd: process.cwd() 
}) 

var stream = ansi({ chunked: false }) 
    , file = fs.createWriteStream('browserify.html', 'utf8') 

npm.stdout.pipe(stream) 
npm.stderr.pipe(stream) 

stream.pipe(file, { end: false }) 

stream.once('end', function() { 
    file.end('</pre>\n') 
}) 

file.write('<pre>\n'); 
1

有一對夫婦的過濾器,SSH2shell適用於來自命令的輸出。第一個從響應中刪除非標準ASCII,然後移除顏色格式代碼。

在v1.6.0中,我添加了pipe()/ 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) 
相關問題