LoginSignup
2
1

More than 5 years have passed since last update.

Node.jsで外部コマンドの同時実行数を制御する

Last updated at Posted at 2017-04-26

外部コマンドが大量に同時実行されるとシステムが不安定になるので同時実行数を制御するサンプル

インストール

npm i execa semaphore

モジュール定義

command.js
const execa = require('execa');
const semaphore = require('semaphore');

class Command{
  constructor(num){
    this.sem = semaphore(num || 1);
  }
  cmdAsync(cmdpath, cmdlist){
    return new Promise((resolve, reject) => {
      this.sem.take(() => {
        execa(cmdpath, cmdlist).then(result => {
          this.sem.leave()
          resolve(result)
        }).catch(e => {
          this.sem.leave()
          reject(e)
        })
      })
    })
  }
}
module.exports = Command

サンプル

const Command = require('./command.js')
const com = new Command()
com.cmdAsync("sleep", ["1"]).then(console.log)
com.cmdAsync("sleep", ["1"]).then(console.log)
com.cmdAsync("sleep", ["1"]).then(console.log)
com.cmdAsync("sleep", ["1"]).then(console.log)
com.cmdAsync("sleep", ["1"]).then(console.log)
com.cmdAsync("sleep", ["1"]).then(console.log)
com.cmdAsync("sleep", ["1"]).then(console.log)
com.cmdAsync("sleep", ["1"]).then(console.log)
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1