How to pause process in node js using spawn

Viewed 3696

Is there any way, how to pause process in node js?

          const { spawn } = require('child_process');

          const process = spawn("run.cmd");

          process.stdout.on('data', (data) => {
            console.log(`stdout: ${data}`);
          });

          process.stderr.on('data', (data) => {
            console.log(`stderr: ${data}`);
          });

          process.on('close', (code) => {

          });

I want call somethink like this: process.pause(), process.continue().

Or some system call using cmd?

I am using windows.

Thank you for any help.

4 Answers

You can find out the process PID and use linux command to pause/resume process by PID.
You can change your code to process = spawn(cmd & echo $! > txt).
It would save your cmd process PID to txt, and then you can use fs to read the PID.

Now you have PID, run exec() to pause process kill -STOP <PID> or resume stopped cmd kill -CONT <PID>.
These two are unix command, should work fine.

I specifically made a library to pause/resume processes from Node.js on Windows, ntsuspend.

const { spawn } = require('child_process');
const ntsuspend = require('ntsuspend');
const process = spawn("run.cmd");
ntsuspend.suspend(process.pid);
ntsuspend.resume(process.pid);

If you're using Linux or MacOS

const { spawn } = require('child_process');
const ntsuspend = require('ntsuspend');
const process = spawn("run.cmd");
process.kill('SIGSTOP');
process.kill('SIGCONT');
Related