2016-08-13 4 views
0

(JSON 문서가 포함 된 파일에서) 읽기 가능 스트림 배열을 만들고 다른 스트림으로 파이프하려고합니다.읽기 콜백 핸들러의 노드 스트림에서 읽은 데이터로 추가 데이터를 추가하는 방법은 무엇입니까?

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)); 

출력 :

파일의 데이터를 통해 ...하지만 난 스트림 파이프에서받는 모든 개체에 대한오고,이 데이터에서이 시작된 파일에서 알고 싶습니다

--- 
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 } 

파일 경로는 추가 객체를 처리하는 데 필요하지만 (jsonStream.on('data') callback)이 추가 데이터를 전달하는 방법을 알지 못합니다.

답변

0

가능한 솔루션은 (내가 더 나은 답변을 얻을하지 않는 한 대답으로이를 표시하고) 다음과

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)); 
    }); 
    }) 
    ; 

출력 :

{ 
    "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 
    } 
}