【问题标题】:Request an external streaming JSON feed in Node在 Node 中请求外部流式 JSON 提要
【发布时间】:2019-11-04 03:37:06
【问题描述】:

Node.js 中,我使用stream-chainstream-json 从本地和远程资源请求流式传输源。以下适用于本地资源,但如何修改它以允许外部资源?我需要先下载文件还是?

const fs              = require('fs');
const { chain }       = require('stream-chain');
const Pick            = require('stream-json/filters/Pick');
const { streamArray } = require('stream-json/streamers/StreamArray');

const path = './feed.json'; // External URL or local file

const pipeline = chain([
    fs.createReadStream(path),
    Pick.withParser({ filter: 'products', once: true }), // Custom: modify feed
    streamArray(),
    data => data
]);

pipeline.on('data', () => {
    counter++;
    console.log(data);
});
pipeline.on('error', error => console.log(error));
pipeline.on('end', () => console.log(`Found ${counter} entries`));

【问题讨论】:

  • 您的意思是带有流式提要的 http url?
  • 你想达到什么目的?

标签: node.js json request streaming


【解决方案1】:

我认为您需要手动下载文件和处理。您可以使用request() 函数获取在线文件。但我同意Suryapratap。但您也可以写入文件并从同一文件读取并继续您的程序。例子

    request("https://reqres.in/api/users",(err, res, body)=>{
        if(err) console.log(err);
    const objectBody = JSON.parse(body)
    fs.writeFile('justtest.json',JSON.stringify(objectBody),err=>{
     if(err) throw err;
    })

     const readable = fs.createReadStream('./justtest.json', "UTF-8");

     readable.on("data", data =>{
           payload = JSON.parse(data);
           console.log(payload);
      } )

 })

你现在可以对你的东西使用对象了。

【讨论】:

    【解决方案2】:

    问题归结为通过网络获得可读流并在运行时对其进行处理。

    我认为这行不通,最后你只需要下载文件,并作为本地文件处理。

    有几种方法可以从网络获取文件:

    var remotePath = "https://....."
    https.get(remotePath, response => {
      var stream = response.pipe(file);
    
      stream.on("finish", function() {
        console.log("done");
      });
    });
    

    或使用请求”

    request(remotePath).pipe(fs.createWriteStream('./remoteFeed.json'))
    

    但最后没有运行时处理的可读流。

    【讨论】:

      猜你喜欢
      • 2017-01-10
      • 2018-08-29
      • 2017-03-28
      • 2015-12-16
      • 1970-01-01
      • 2010-10-29
      • 2017-02-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多