2016-11-04 3 views
-1

ETL 프로세스를 수행하는 Python 스크립트를 실행하고 문서 (내 몽구스 모델의 인스턴스)를 작성하고 저장하는 데 사용할 JSON 객체를 리턴합니다. MongoDB에서. node.js 라이브러리 child_process의 도움으로 올바르게 스크립트를 실행하고 있지만 자식 프로세스가 완료되기 전에 문서가 만들어집니다. Python 스크립트를 비동기 적으로 (Node.js 이벤트 루프를 차단하지 않고) 실행하도록 코드를 수정하고 그 결과를 사용하여 내 몽구스 모델의 문서를 작성해야합니까?child_process 및 moongose. 비동기 적으로 스크립트를 실행하고 model.create에서 결과를 사용하십시오.

// Creates a new Report in the DB (report controller) 
import {spawn} from 'child_process'; 
export function create(req, res) { 

    var json_report = ""; 
    var path2file = path.join(__dirname, "/../../../python_reporter/reports/", "node_connector.py"); 
    var python = spawn('python', [path2file]); 
    var request_body = {}; 

    //We are going to receive a JSON-like string from python 
    python.stdout.on('data', function (data) { 
     json_report += data.toString(); 
    }); 

    python.stderr.on('data', (data) => { 
     console.log(`stderr: ${data}`); 
    }); 

    python.stdout.on('exit', function() { 
     json_report = JSON.parse(json_report); 
     for(var key in req.body){ 
      request_body[String(key)] = req.body[key]; 
     } 
     for(var key in json_report){ 
      request_body[String(key)] = json_report[key]; 
     } 
     console.log(request_body) 
     console.log("JSON object successfully created"); 
    }); 

    return Report.create(request_body) 
     .then(respondWithResult(res, 201)) 
     .catch(handleError(res)); 
} 

답변

1

return 문이 필요없는 경우 'exit'블록에 넣기 만하면됩니다.

python.stdout.on('exit', function() { 
    json_report = JSON.parse(json_report); 
    for(var key in req.body){ 
     request_body[String(key)] = req.body[key]; 
    } 
    for(var key in json_report){ 
     request_body[String(key)] = json_report[key]; 
    } 
    console.log(request_body) 
    console.log("JSON object successfully created"); 

    Report.create(request_body) 
     .then(respondWithResult(res, 201)) 
     .catch(handleError(res)); 

}); 
+0

도움을 주셔서 대단히 감사합니다. –

+0

도움이 되니 기쁩니다! – Zilvinas

관련 문제