Skip to content
Advertisement

Should I use worker or child processes to run my function?

I have two files, main.js and job.js. When a button is clicked in main.js, I want a new, seperate process of the function in job.js to run.

What this process does is launch a new puppeteer browser instance. When the stop button is clicked, this process should be killed by pid. (For this we use process.kill(child.pid)?)

So would I want to use a worker or child process, and if any of those two, how would I implement it so it runs this function?

Important note: every time the start button is clicked, I would like a new process running the function to be started, so the specific process with that pid can be killed.

Advertisement

Answer

I suggest you to use a wrapper module for the child_process module. Example usage with execa module.

Main.js

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
    })

}

This should give you an idea on how to implement it. I suggest to use child_process or any wrapper module. ^^

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement