我有兩個文件,main.js和job.js。當在 main.js 中單擊一個按鈕時,我希望在job.js中運行一個新的、單獨的函數進程。
這個過程的作用是啟動一個新的 puppeteer 瀏覽器實例。當停止按鈕被點擊時,這個進程應該被pid殺死。(為此我們使用process.kill(child.pid)
?)
那麼我是否想要使用工作進程或子進程,如果這兩者中的任何一個,我將如何實現它以運行此功能?
重要提示:每次單擊開始按鈕時,我都希望啟動一個運行該功能的新進程,因此可以殺死具有該 pid 的特定進程。
我建議您為模塊使用包裝器child_process
模塊。使用execa模塊的示例用法。
主程序
const { execa } = require('execa')
// function for spawning a process with cancel handle!.
async function spawnSubprocess(command, args, cb) {
let subprocess = execa(command, args);
// create a cancel function for later usage!.
function cancel() {
if(subprocess) {
subprocess.kill('SIGTERM', {
// wait for it to terminate before killing it.
forceKillAfterTimeout: 1500
});
// set to null so it won't be killed mutliple times.
subprocess = null
}
}
// add the event listener to subprocess when it's done!
// Can be used for logging or for correctly awaiting a process
// termination before proceeding.
subprocess.then(() => {
subprocess = null
cb()
})
.catch(err => {
subprocess = null
cb(err)
})
// return the cancel handler !.
return cancel
}
// reference to the last cancel. It has to be accessible in
// onClickHandler ofc!.
var processCancel = null
// call this function on click.
// keep the processCancel in scope!
function onClickHandler() {
// first, check if a process is already running
if(typeof processCancel === 'function') {
console.log('Process already running. Calling cancel!')
// the process is not directly terminated. You amy have
// 2 seconds where multiple instances are running but that's not a big deal i guess.
processCancel()
}
// spawn the new process !
// adjust the path to job.js ofc!.
processCancel = spawnSubprocess('node', ['job.js'], (err) => {
// on done callback!. Log some information!.
if(err) {
console.error('Process error ', err)
} else {
console.log('process stopped / DONE')
}
processCancel = null
})
}
這應該讓您了解如何實施它。我建議使用child_process
或任何包裝模塊。^^
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句