简体   繁体   English

在node.js中执行命令后杀死进程

[英]Kill process after execute command in node.js

I would like to kill process (or exit them) after my commands will complete. 我想在命令完成后终止进程(或退出它们)。 I have this code, but process exits immediately. 我有此代码,但进程立即退出。

var gplay = require('google-play-scraper');

gplay.list({
    category: gplay.category.GAME_ACTION,
    collection: gplay.collection.TOP_FREE,
    start: 0,
    num: 120
  })
  .then(console.log, console.log);

gplay.list({
    category: gplay.category.GAME_ACTION,
    collection: gplay.collection.TOP_FREE,
    start: 120,
    num: 120
  })
  .then(console.log, console.log);
process.exit();

I run this by node script.js > output.txt , because i want to write output to file. 我通过node script.js > output.txt运行它,因为我想将输出写入文件。 I don't know other method. 我不知道其他方法。

Javascript is highly asynchronous in nature that means after invoking the first function call it will immediately move to the next statement. Java本质上是高度异步的,这意味着在调用第一个函数调用后,它将立即移至下一条语句。 In your case there are two possible ways: 在您的情况下,有两种可能的方法:

  1. Either put the next line of execution inside the then() of the first one and put exit() inside the then() block of second call. 将下一条执行行放在第一个调用的then()内,然后将exit()放在第二个调用的then()块内。
  2. Use async https://caolan.github.io/async/ 使用异步https://caolan.github.io/async/
  3. Or simply remove exit(); 或者简单地删除exit();

You can use Promise.all 您可以使用Promise.all

It returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises. 它返回一个Promise,当可迭代参数中的所有promise已解决或可迭代参数不包含promise时,它会解决。 It rejects with the reason of the first promise that rejects. 它以第一个承诺被拒绝的理由拒绝。

The callback displayThenExit will display the results then exits the node process 回调displayThenExit将显示结果然后退出节点进程

var gplay = require('google-play-scraper');

var p1 = gplay.list({
    category: gplay.category.GAME_ACTION,
    collection: gplay.collection.TOP_FREE,
    start: 0,
    num: 2
  })  

var p2 = gplay.list({
    category: gplay.category.GAME_ACTION,
    collection: gplay.collection.TOP_FREE,
    start: 2,
    num: 2
  })  
var displayThenExit = function(result){
    console.log(result);
    process.exit(0);
}

Promise.all([p1, p2]).then(displayThenExit, console.log);

ps: I set num: 2 to limit the number of entries returned for testing purpose ps:我将num: 2设置为限制出于测试目的返回的条目数

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

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