hi,大家好。
问一个 http 的问题。我用 node.js 把 shell 的 stdout pipe 到 http.response 上了,设置了 chunked ,但是页面要卡一段很长的时间(经常是要等后台的输出全完了)才显示。我希望能边刷 shell 输出,边在浏览器上页面 shell 的输出。
求帮忙。谢谢!
|  |      1bdbai      2016-08-12 17:49:36 +08:00 via Android 你用了 jQuery 处理 ajax 请求吗? 这种场景适合用原生 XMLHTTPRequest 直接处理请求。我最近在做一个项目也用到了 chunked 实时回显文本,你可以参考一下: https://github.com/bdbai/nthskeys-node/blob/master/app/apis/Extractor.js | 
|  |      2magicdawn      2016-08-12 17:52:23 +08:00 我之前碰到过, 试试设置 content-type: text/plain 然后拿 chrome 试试, 应该也跟浏览器有关系 | 
|  |      3gimp      2016-08-12 18:08:25 +08:00 我用 socket.io 做过类似的东西, web 端输入网址,后台 ping ,然后实时返回给 web 页面展示。  我也不知道主流的是不是这么搞,反正是实现了类似的功能,仅供参考 https://github.com/sincerefly/online-ping-demo | 
|  |      7iahu OP 多谢大家的回复。 换成 webSocket 是可以的。 HTTP 设置`content-type: text/plain`没用,但是我也记得以前做过的项目设置后在 Chrome 下是有效的。 | 
|  |      8serial      2016-08-16 13:13:25 +08:00 不要用 pipe , stdout 有行缓冲的,缓冲区满了行才会发出去。自己 write flush | 
|  |      9Kei      2016-08-19 14:23:51 +08:00 ``` let child = shell.exec(command, {async: true}, function (err, stdout, stderr) { cb(err, {err: stderr}) }) child.stdout.on('data', function (data) { app.io.emit('output', {output: data}) }) ``` |