2013-06-25 35 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"); 
    }); 

我希望这将帮助你。

相关问题