通过expressjs从子进程到浏览器的stdout流 [英] Stream stdout from child process to browser via expressjs

查看:128
本文介绍了通过expressjs从子进程到浏览器的stdout流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个使用 nodejs express child_process.spawn 。一个要求是,我们需要在运行时生成一个进程,并捕获它的输出并将其呈现给用户。



我们有工作。但是,我们需要找出流式输出的方法,而不是等到子进程存在。



我们环顾四周,找不到任何明确的例子,并想知道有没有人有任何想法?


$ b $一切都在工作。我们只是不关心在显示整个输出之前必须等待命令完成的用户体验。如果我们可以流式传输,这将是理想的,因为stdout数据事件被触发,浏览器将使用新的数据更新。就像现在一样,它的大块是相反的,而不是一个大的blob ..所以它很适合做这个。

解决方案

Express路由的响应对象也是可写流的实例,因此允许您将子进程' stdio 流管道到响应。

  app.get('/ path',function(req,res){
var child = spawn('ls',[' - al']);
child.stdout.pipe(res);
});


We have an app built using nodejs, express and child_process.spawn. One requirement is that we need to spawn a process at runtime and capture it's output and present it to the user.

We have that working. However, we need to figure out a way to stream the output instead of waiting until the child process exists.

We've looked around and couldn't find any clear cut examples and were wondering if anyone here had any ideas?

Everything is working. We just don't care for the user experience of having to wait for the command to finish before showing the entire output. If we could stream it, that would be ideal so as the stdout data event was triggered, the browser would update with the new data. As right now it does come in chunks as opposed to one big blob.. so it's suited quite nicely to do this.

解决方案

The response object of an Express route is also an instance of writable stream, so that allows you to pipe the child process' stdio streams to the response.

app.get('/path', function(req, res) {
  var child = spawn('ls', ['-al']);
  child.stdout.pipe(res);
});

这篇关于通过expressjs从子进程到浏览器的stdout流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆