Kill a Child Process in Node.js while still running Server

321 Views Asked by At

I am trying to kill a child process I have running within my server. Basically the child process runs johnny-five code I've written in an online terminal in React to my server. When I run the child process, the code works great but if I want to kill the child process I cant do so without stopping the server. I've tried doing so with Control-C and .exit() but neither seem to work.

codeRouter
  .post('/codeAPI', (req, res) => {

    console.log(req.body)
    let fileName = `johnnyFiles/${req.body.currentFile}`
    fs.writeFileSync(fileName, req.body.currentCode, (err) => {
      if (err) throw err
    })
    let id = shortid.generate()
    let fileObject = {
      fileName: req.body.currentFile,
      fileContents: req.body.currentCode,
      ID: id
    }
    data = [fileObject, ...data]
    fs.writeFileSync('data/fileData.json', JSON.stringify(data), (err) => {
      if (err) throw err
    })

    res.json(data)
    ///////////////////////////////////////////
    let nodeSpawn = spawn('node', [fileName], {
      //detached: true,
      shell: true
    })
    nodeSpawn.stdout.on('data', (data) => {
      console.log("OUTPUT", data.toString())
    })
    nodeSpawn.stderr.on('data', (data) => {
      console.log("ERRORS", data.toString())
    })
    nodeSpawn.on('exit', (code) => {
      console.log(`Child exited with code ${code}`)
      nodeSpawn.kill('SIGINT')
    })



  })

`

1

There are 1 best solutions below

0
Pavlo Rosa On

You can use the linux command line.

To see the running processes use the command, use:

pgrep node

To kill the process you can use:

kill <pid>

Or to force the shutdown

kill -9 <pid>

Or if you want kill all node processes

kill $(pgrep node)