pipe道subprocessstdout&标准input到浏览器在node.js&browserify

我试图将一个child_process的标准输出和标准input到浏览器并显示在一个HTML页面中。 我正在使用browserify来让node.js在浏览器上运行。 我产生child_process的代码就像这样。

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创build了一个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服务器,并在浏览器中传递结果给它。 有什么其他方法可以做到吗? 谢谢

你应该看看hyperwatch ,它将服务器端的stdout / stderr传递给浏览器,并呈现完全像它在terminal中显示的样子(包括颜色)。

如果它不能完全解决你的问题,阅读代码应该至less帮助你。 它使用引擎盖下的hypernal为了将terminal输出转换为html。

我不知道这是否迟到,但我设法从浏览器开始从这个代码,只适用于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"); }); 

我希望这会帮助你。

我认为前端的NPM模块也可以做你想做的事情 –

https://github.com/mthenw/frontail

我已经使用它,它的工作原理