Categories
JavaScript Answers

How to spawn and kill a process in Node.js?

Spread the love

To spawn and kill a process in Node.js, we use the tree-kill package.

For instance, we write

const kill = require("tree-kill");
const spawn = require("child_process").spawn;

const scriptArgs = ["myScript.sh", "arg1", "arg2", "youGetThePoint"];
const child = spawn("sh", scriptArgs);

button.on("someEvent", () => {
  kill(child.pid);
});

to call spawn to run the 'sh' command with the scriptArgs command line arguments.

And then we call kill to kill the process with the child.pid process ID.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *