문제

나는 이상한 문제가있다.

Node App (외부, 포크가 없음)에서 프로세스를 생성해야합니다.이 자식 프로세스는 출력을 DB로 되돌리고 저장해야합니다.내가 지금하는 방식은 내 데이터의 각 줄 (JSON)을 반향시키고 stdout에서 오는 것을 듣는 것입니다.

하위 코드 :

var cntSent=0
for (var j = 0, lUF = uniqueFlyers.length; j < lUF; j++) {
  var products = uniqueFlyers[j].products;
  for (var k = 0, lP = products.length; k < lP; k++) {
    var pstr = products[k].product;
    this.echo(pstr);
    cntSent+=1;
  }
}
console.log(cntSent);
.

end, cntent= 10000.

노드 측면 :

var cntReceived
proc.stdout.on('data', function(line) {
  cntReceived+=1;
  console.log(line);
});
proc.on('close', function (code) {
  console.log(cntReceived);
});
.

끝에서 cntreceived= 3510.

내 모든 데이터를 출력 할 수는 있지만 함께 집계되어 큰 덩어리로 제공됩니다. 내 아이디어는 파일에 쓰고 노드로 파일을 처리하는 것입니다.하지만 중복 된 것처럼 보이고 데이터를 처리하고 싶습니다.가장 정확하고 빠른 방법에 대한 제안은 무엇입니까?

편집 : 평소처럼, 질문을 쓰는 것은 나를 생각하게 만들었습니다.나는 단지 바보이며 데이터를 버퍼링하는 것이 더 나은 다음 구문 분석 할 것입니까?그것은 JSON Goddamnit입니다!

도움이 되었습니까?

해결책

파일에 데이터를 쓸 필요가 없으면 파일을 처리 할 필요가 없습니다.그것을 처리하기 전에 전체 데이터를 버퍼링해야합니까?

출력하는 데이터가 JSON에있는 경우 JSONStream 를 사용하여 제안합니다.부모 코드.이렇게하면 플라이에서 출력을 구문 분석 할 수 있습니다.다음은 예제입니다.

자식 코드는 JSON 배열을 출력합니다.

// Child code
console.log('['); // We'll output a JSON array
for (var j = 0, lUF = uniqueFlyers.length; j < lUF; j++) {
  var products = uniqueFlyers[j].products;
  for (var k = 0, lP = products.length; k < lP; k++) {
    var pstr = products[k].product;
    console.log(JSON.stringify(pstr)); // output some JSON
    if ((j !== lUF - 1) && (k !== lP - 1))
        console.log(','); // output commas between JSON objects in the array
    cntSent+=1;
  }
}
console.log(']'); // close the array
.

부모 코드 가이 JSON 배열을 읽고 처리 할 수 있습니다.우리는 배열의 모든 요소를 선택하기 위해 * 선택기를 사용합니다.그런 다음 JSONStream이 각 JSON 문서를 구문 분석 할 때 하나씩 나오게됩니다.이 데이터가 있으면 쓰기 가능한 스트림 를 사용할 수 있습니다.물체가 그 다음에 뭔가를해라.

// Parent code
var stream = require('stream');
var jsonstream = require('JSONStream').parse('*');
var finalstream = new stream.Writable({ objectMode: true }); // this stream receives objects, not raw buffers or strings
finalstream._write = function (doc, encoding, done) {
    console.log(doc);
    done();
};

proc.stdout.pipe(jsonstream).pipe(finalstream);
.

다른 팁

var cntReceived
proc.stdout.on('data', function(line) {
  var arr = data.split('\n');
  cnt+=arr.length-1;
  console.log(line);
});
proc.on('close', function (code) {
  console.log(cntReceived);
});

Output : cntReceived = 10000

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top