NodeJS -> 在每个 res.write(data) 之后获取数据字符串

NodeJS -> GET data string after each res.write(data)

我在本地主机上有两个 NodeJS 应用程序 运行。

1 号申请请求 /generatedData 表格 2 号申请(下方)使用 superagent.js:

request = require('superagent');
request.get('http://localhost:3000/generatedData')
.end(function(err, res) {
    if (err) {
        console.log(err);
    } else {
        console.log(res.text);
    }
});

2 号应用程序生成数据并将其写入响应(下)

router.get('/generatedData', function (req, res) {

    res.setHeader('Connection'          , 'Transfer-Encoding');
    res.setHeader('Content-Type'        , 'text/html; charset=utf-8');
    res.setHeader('Transfer-Encoding'   , 'chunked');

    var Client = someModule.client;  
    var client = Client();

    client.on('start', function() {  
        console.log('start');
    });

    client.on('data', function(data) {
        res.write(data);
    });

    client.on('end', function(msg) { 
        client.stop();
        res.end();
    });

    client.on('err', function(err) { 
        client.stop();
        res.end(err);
    });

    client.on('stop', function() {  
        console.log('stop');
    });

    client.start();

    return;

});

在 1 号应用程序中,我想使用正在写入的数据。 我等不及 request.end,因为生成的数据可能很大,需要很长时间才能完成。

我如何获取 2 号应用程序写入 response 的数据?

这是正确的方向吗?最好的方法是什么?

谢谢, 阿萨夫

要使用 App No.1 中写入的数据,您可以使用 Node.js http 模块并监听响应对象的 data 事件。

const http = require('http');

const req = http.request({
  hostname: 'localhost',
  port: 3000,
  path: '/generatedData',
  method: 'GET'
}, function(res) {
  res.on('data', function(chunk) {
    console.log(chunk.toString());
    // do whatever you want with chunk
  });
  res.on('end', function() {
    console.log('request completed.');
  });
});

req.end();
第一个应用程序缺少

Streaming

你可以使用一些东西:

require('superagent')
  .get('www.streaming.example.com')
  .type('text/html')
  .end().req.on('response',function(res){
      res.on('data',function(chunk){
          console.log(chunk)
      })
      res.pipe(process.stdout)
  })

取参考表格

如果您想写入文件,请使用类似这样的东西...

const request = require('superagent');
const fs = require('fs');

const stream = fs.createWriteStream('path/to/my.json');

const req = request.get('/some.json');
req.pipe(stream);