2013-06-25 51 views
5

我試圖管道標準輸出&標準輸入的child_process到瀏覽器&顯示它在HTML頁面。我正在使用browserify來讓node.js在瀏覽器上運行。我產生child_process的代碼就像這樣。管道子進程標準輸出和標準輸入瀏覽器在node.js和browserify

var child = require('child_process'); 

var myREPL = child.spawn('myshell.exe', ['args']); 

// myREPL.stdout.pipe(process.stdout, { end: false }); 

process.stdin.resume(); 

process.stdin.pipe(myREPL.stdin, { end: false }); 

myREPL.stdin.on('end', function() { 
    process.stdout.write('REPL stream ended.'); 
}); 

myREPL.on('exit', function (code) { 
    process.exit(code); 
}); 

myREPL.stdout.on('data', function(data) { 
    console.log('\n\nSTDOUT: \n'); 
    console.log('**************************'); 
    console.log('' + data); 
    console.log('=========================='); 
}); 

我使用browserify創建了一個bundle.js,我的html看起來像這樣。

<!doctype html> 
    <html lang="en"> 
     <head> 
      <meta charset="utf-8" /> 
      <title></title> 
      <!--[if IE]> 
      <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> 
      <![endif]--> 
      <script src="bundle.js"></script> 
      <script src="main.js"></script> 
     </head> 
     <body> 

     </body> 
    </html> 

我試圖避免運行http服務器,並在瀏覽器中將結果傳遞給它。有什麼其他的方式可以做到嗎? 謝謝

+0

什麼問題?任何錯誤消息? –

+0

是的,所以在瀏覽器process.stdin&process.stdout是未定義的,這是有道理的,因爲瀏覽器不會支持它。但我不知道如何解決它 – ssarangi

回答

2

你應該看看hyperwatch,它將服務器端stdout/stderr傳遞給瀏覽器,並呈現它完全像它在終端中顯示的樣子(包括顏色)。

如果它不能完全解決您的問題,閱讀代碼應該至少可以幫助您。它使用引擎蓋下的hypernal以將終端輸出轉換爲html。

+0

感謝的人,真的很感謝 – stringparser

+0

非常好的東西,一個完整的例子和開放許可證:)謝謝 – Andrei

+0

我認爲前端NPM模塊也可以做同樣的事情 - https:// github.com/mthenw/frontail,我已經使用它,它的工作原理 –

1

我不知道這是遲到了,但我設法從瀏覽器開始運行一個程序,只能在linux上運行(我使用ubuntu)。您將不得不使用stdbuf -o0前綴運行交互式程序。

var child = require('child_process'); 
var myREPL = child.spawn('bash'); 

process.stdin.pipe(myREPL.stdin); 

myREPL.stdin.on("end", function() { 
    process.exit(0); 
}); 

myREPL.stdout.on('data', function (data) { 
    console.log(data+''); 
}); 

myREPL.stderr.on('data', function (data) { 
    console.log('stderr: ' + data); 
}); 

然後將使其對瀏覽器的工作,你只需要添加socket.io

var myREPL = child.spawn(program); 
    myREPL.stdin.on("end", function() { 
     socket.emit('consoleProgramEnded'); 
    }); 

    myREPL.stdout.on('data', function (data) { 
     socket.emit('consoleWrite',data+''); 
    }); 

    myREPL.stderr.on('data', function (data) { 
     socket.emit('consoleWrite',data+''); 
    }); 

    socket.on('consoleRead',function(message){ 
     console.log("Writing to console:"+message); 
     myREPL.stdin.write(message.replace("<br>","")+"\n"); 
    }); 

我希望這將幫助你。

相關問題