My nodejs application on receiving a particular request spawns a child process using spawn(I can't use exec as the output is large and don't know if I can add call back to spawned processes) that prepares the response.

I want the child process to send the response or the main process to wait till child prepares the response and exits.

The problem is that the main process doesn't wait for child.

I have coded something like this

inputQuery: function(req, res){
                 var output="";
                 var query = "printjson(db.getCollectionNames())";

                 var temp  = spawn("mongo", ["mongoweb ", "-eval", query]);
                 temp.on('error', function (err){
                         console.log(err);
                 });
                 temp.stdout.on('data', function(data){
                         output += data;
                 });

                 temp.stderr.on('data', function(data){
                         console.log(data);
                 });

                 temp.on("exit", function(code){
                         console.log("Output is :" + output);
                         res.send(output); // Either send response here or after the log message below

                 });

                 console.log("I want this to wait or let child respond");
}

I am really stuck and have no idea how to do this. Please help. Thanks in advance.

有帮助吗?

解决方案

Well what I end up doing was to spawn a process that cat the result in a temp file. Then pass a message to parent when child is done (basically a flag). Wait for this message and on getting the message, start another process to repeatedly copy the buffer and keep dumping stdout in a loop till done.

NOTE: For most cases, you have an option to change the size of exec buffer and and that should work as you could make it pretty big. I guess it can go to something like 1 or 2 MB but ya I am not sure on that.

Would be happy is someone got a better idea !!!

@Krasimir let me know how you solve it.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top