首页 > 解决方案 > 如何在 nodeJs 中使用 stream-json 中的管道写入文件?

问题描述

我正在尝试使用stream-json读取 zip,解压缩,然后将其写入文件。我想我不明白如何使用图书馆。

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

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_meta\b/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 来创建它自己的?

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

标签: javascriptnode.jsjsonnode-streams

解决方案


我不想计算任何东西,我只想写入文件

在这种情况下,您需要将令牌/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')
]);

推荐阅读