在 Node.js
中,我使用 stream-chain
和 stream-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`));
最佳答案
问题归结为通过网络获得可读流并在运行时处理它。
我认为这行不通,最后你必须只下载文件,并作为本地文件处理。
有几种方法可以从网络上获取文件:
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'))
但最后没有运行时处理的可读流。
关于node.js - 在 Node 中请求外部流式 JSON 提要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56700827/