获取数据后,节点子进程将持续运行而不会关闭

时间:2019-05-14 09:06:38

标签: javascript node.js javascript-events child-process spawn

我正在做一个回送项目,需要运行后台作业。生成节点子进程。由于我是初学者,因此文档很少让人感到困惑。 https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options

parent.js

const path = require("path");

const spawn = require('child_process').spawn;

let child = spawn('node', [__dirname + '../../worker/worker.js']);

child.stdout.on('data', function (data) {
      console.log('data available ' + data);
});

child.stderr.on('data', function (data) {
     console.log('There was an error: ' + data);
});

worker.js

function jobListener() {


    let query = { jobname: "countProvider"}
    let result = Job.findOne({ where: query }, function(err, instance) {
        if(err) {
            console.log('Error', err);
        }
      // console.log(instance);
    });

    while (!result) { 
        console.log(result);
       // await sleep(5000);
        console.log('checking for job in mongodb with a delay of 5 seconds');
    }
    if(result) {
        fetchProcedureRequest();
    }
}

jobListener();

function fetchProcedureRequest() {
    console.log('Fetching pREquest');
}

我要实现的目标是在子进程中获取数据。但是,当父级中有可用数据时,如何关闭/退出该过程。有人请帮助,任何建议将不胜感激。

1 个答案:

答案 0 :(得分:0)

也许您可以使用它,请点击How to kill childprocess in nodejs?

var proc = require('child_process').spawn('mongod'); proc.kill('SIGINT');