LoginSignup
0
0

More than 1 year has passed since last update.

node.js child_process spawn を async queueで順番待ちさせる方法

Posted at
  1. node.jsで
  2. 時間のかかるローカル処理。。例えばStable Diffustionとか・・重々しいバッチ処理とかをchild_processで処理しているが、
  3. ローカルの処理はspawnで非同期にしているので
  4. これをasync queueで待ち行列にしたい。

やりかた

const { spawn } = require('node:child_process')
const async = require('async')

const heavyTask = (data) => {
  return new Promise((resolve) => {
    // なんかでかくて重い処理、例えばrm -rf / など。
    const result = spawn('very_heavy_task.sh', [])
    // 処理が終わった時に呼ばれる
    result.on('close', (code) => {
        resolve()
    }
  }
}

const workQueue = async.queue(heavyTask)
workQueue.push({data})

重い処理全体をPromise()で包んで、処理が終わったハンドラ内でresolve()するのがポイント。

0
0
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
0
0