Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

166
Vistas
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.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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. ^^

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda