How to add additional data with data read from a node stream in read callback handler?

穿精又带淫゛_ 提交于 2020-01-25 07:21:07

问题


I'm creating an array of Readable streams (from files containing JSON docs) and am trying to pipe them to another stream.

The data in the files is coming through… but for every object I receive in the piped to stream, I would like to know from which file this data originated from:

var fs = require('fs');
var path = require('path');
var JSONStream = require('JSONStream');

var tmp1 = path.join(__dirname, 'data', 'tmp1.json');
var tmp2 = path.join(__dirname, 'data', 'tmp2.json');

var jsonStream = JSONStream.parse();
jsonStream.on('data', function (data) {
  console.log('---\nFrom which file does this data come from?');
  console.log(data);
});

[tmp1, tmp2].map(p => {
  return fs.createReadStream(p);
}).forEach(stream => stream.pipe(jsonStream));

Outputs:

---
From which file does this data come from?
{ a: 1, b: 2 }
---
From which file does this data come from?
{ a: 3, b: 4 }
---
From which file does this data come from?
{ a: 5, b: 6 }
---
From which file does this data come from?
{ a: 100, b: 200 }
---
From which file does this data come from?
{ a: 300, b: 400 }
---
From which file does this data come from?
{ a: 500, b: 600 }

The file path is needed to further process the object read (in jsonStream.on('data') callback) but I don't know how to go about passing this additional data.


回答1:


A possible solution follows (am marking this as the answer unless I get a better answer):

var fs = require('fs');
var path = require('path');
var JSONStream = require('JSONStream');
var through = require('through2');

var tmp1 = path.join(__dirname, 'data', 'tmp1.json');
var tmp2 = path.join(__dirname, 'data', 'tmp2.json');

[tmp1, tmp2]
  .map(p => fs.createReadStream(p))
  .map(stream => [path.parse(stream.path), stream.pipe(JSONStream.parse())])
  .map(([parsedPath, jsonStream]) => {
    return jsonStream.pipe(through.obj(function (obj, _, cb) {
      this.push({
        fileName: parsedPath.name,
        data: obj
      });
      cb();
    }));
  })
  .map(stream => {
    stream.on('data', function (data) {
      console.log(JSON.stringify(data, null, 2));
    });
  })
  ;

Output:

{
  "fileName": "tmp1",
  "data": {
    "a": 1,
    "b": 2
  }
}
{
  "fileName": "tmp1",
  "data": {
    "a": 3,
    "b": 4
  }
}
{
  "fileName": "tmp1",
  "data": {
    "a": 5,
    "b": 6
  }
}
{
  "fileName": "tmp2",
  "data": {
    "a": 100,
    "b": 200
  }
}
{
  "fileName": "tmp2",
  "data": {
    "a": 300,
    "b": 400
  }
}
{
  "fileName": "tmp2",
  "data": {
    "a": 500,
    "b": 600
  }
}


来源:https://stackoverflow.com/questions/38932502/how-to-add-additional-data-with-data-read-from-a-node-stream-in-read-callback-ha

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!