简体   繁体   English

在node.js中使用子进程,在命令完成时调用函数

[英]using child process in node.js, calling function on completion of command

I am making a program in which I need to execute some linux command through node.js. 我正在制作一个程序,其中需要通过node.js执行一些linux命令。

like this 像这样

final_command.stdout.on('data', function(data) { 
    fs.writeFile(dates+'.html', data, function(err){
        if(err){
            return console.error(err);
        }
    });
});

final_command.stderr.on('data', function(data) { 
    console.log('stderr: '+data);
});

final_command.on('exit', function(code) { 

}); 

Here I am saving the output to a HTML file. 在这里,我将输出保存到HTML文件。

Now to run the other part of the program 现在运行程序的另一部分

Should I put it in the final_command.on part or how can I call a function in that part? 我应该将其放在final_command.on部分中,还是应该在该部分中调用函数?

I know that's a lame question but still. 我知道这是一个la脚的问题,但仍然如此。

The question 'Should I put it in the final_command.on part or how can I call a function in that part?' 问题“我应将其放在final_command.on部分还是该部分中如何调用函数?” is unclear. 尚不清楚。 Do you mean to ask how to fill-in the final_command? 您是要问如何填写final_command吗? If so, here is how you will do it. 如果是这样,这是您将如何做。

var spawn = require('child_process').spawn;
var fs = require('fs');
var dates = 'dates';

var command = 'ls';
var final_command = spawn(command);

final_command.stdout.on('data', function childoutdata) { 
    fs.writeFile(dates+'.html', data, function childdatawrite(err){
        if(err){
            return console.error(err);
        }
    });
});

final_command.stderr.on('data', function(data) { 
    console.log('stderr: '+data);
});

final_command.on('exit', function childexit(code) { 

});

If the question is how and when you continue the work after the file operation, it depends: If the child process action, data arrival and writing into the file should precede everything, then you should write your rest of the code in childdatawrite. 如果问题是在文件操作之后如何以及何时继续工作,则取决于:如果子进程操作,数据到达和写入文件的操作应先于一切,则应在childdatawrite中编写其余代码。 If the child process is all what you care about, then you should write your rest of the code in childexit. 如果子进程正是您所关心的,那么您应该在childexit中编写其余代码。 If the rest of the code can run out of sync with the child business, then can place your code outside of the current block. 如果其余代码可能与子业务不同步,则可以将您的代码放在当前块之外。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM