【问题标题】:NodeJS -> GET data string after each res.write(data)NodeJS -> 在每个 res.write(data) 之后获取数据字符串
【发布时间】:2023-12-18 03:21:01
【问题描述】:

我在 localhost 上运行了两个 NodeJS 应用程序。

1 号应用程序使用 superagent.js 请求/generatedData 2 号应用程序(下):

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 时如何获取数据?

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

谢谢, 阿萨夫

【问题讨论】:

    标签: node.js http httprequest httpresponse superagent


    【解决方案1】:

    要使用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();
    

    【讨论】:

      【解决方案2】:

      第一个应用程序中缺少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)
        })
      

      参考表格Streaming data events aren't registered

      如果您想写入文件,请使用类似的内容...

      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);
      

      【讨论】:

        最近更新 更多