我如何使用管道从流json写入文件,在nodeJs?



我试图使用stream-json读取压缩,解压缩,然后将其写入文件。我想我不知道如何使用图书馆。

根据上面的链接,他们有这个例子:

const {chain}  = require('stream-chain');
const {parser} = require('stream-json');
const {pick}   = require('stream-json/filters/Pick');
const {ignore} = require('stream-json/filters/Ignore');
const {streamValues} = require('stream-json/streamers/StreamValues');
const fs   = require('fs');
const zlib = require('zlib');
const pipeline = chain([
fs.createReadStream('sample.json.gz'),
zlib.createGunzip(),
parser(),
pick({filter: 'data'}),
ignore({filter: /b_metab/i}),
streamValues(),
data => {
const value = data.value;
// keep data only for the accounting department
return value && value.department === 'accounting' ? data : null;
}
]);
let counter = 0;
pipeline.on('data', () => ++counter);
pipeline.on('end', () =>
console.log(`The accounting department has ${counter} employees.`));

然而,我不想计数任何东西,我只想写入文件。这是我的工作:

function unzipJson() {
const zipPath = Path.resolve(__dirname, 'resources', 'AllPrintings.json.zip');
const jsonPath = Path.resolve(__dirname, 'resources', 'AllPrintings.json');
console.info('Attempting to read zip');
return new Promise((resolve, reject) => {
let error = null;
Fs.readFile(zipPath, (err, data) => {
error = err;
if (!err) {
const zip = new JSZip();
zip.loadAsync(data).then((contents) => {
Object.keys(contents.files).forEach((filename) => {
console.info(`Writing ${filename} to disk...`);
zip.file(filename).async('nodebuffer').then((content) => {
Fs.writeFileSync(jsonPath, content);
}).catch((writeErr) => { error = writeErr; });
});
}).catch((zipErr) => { error = zipErr; });
resolve();
} else if (error) {
console.log(error);
reject(error);
}
});
});
}

然而,我不能轻易地添加任何处理,所以我想用stream-json代替它。这是我的部分尝试,因为我不知道如何完成:

function unzipJson() {
const zipPath = Path.resolve(__dirname, 'resources', 'myfile.json.zip');
const jsonPath = Path.resolve(__dirname, 'resources', 'myfile.json');
console.info('Attempting to read zip');
const pipeline = chain([
Fs.createReadStream(zipPath),
zlib.createGunzip(),
parser(),
Fs.createWriteStream(jsonPath),
]);
// use the chain, and save the result to a file
pipeline.on(/*what goes here?*/)

稍后我打算添加额外的json文件处理,但我想在我开始添加额外的功能之前学习基础知识。

我不能产生一个最小的例子不幸的是,因为我不知道什么进入pipeline.on函数。我在努力理解我应该做什么,而不是我做错了什么。

我也看了相关的stream-chain,它有一个示例,结尾是这样的:

// use the chain, and save the result to a file
dataSource.pipe(chain).pipe(fs.createWriteStream('output.txt.gz'));`

但是在任何时候文档都没有解释dataSource来自哪里,我认为我的链通过从文件中读取zip来创建它自己的?

我应该如何使用这些流库写入文件?

我不想计数任何东西,我只想写到文件

在这种情况下,您需要将令牌/JSON数据流转换回可以写入文件的文本流。您可以使用库的Stringer。它的文档还包含一个示例,似乎更符合您想要做的事情:
chain([
fs.createReadStream('data.json.gz'),
zlib.createGunzip(),
parser(),
pick({filter: 'data'}), // omit this if you don't want to do any processing
stringer(),
zlib.Gzip(),            // omit this if you want to write an unzipped result
fs.createWriteStream('edited.json.gz')
]);

最新更新