Skip to content

Instantly share code, notes, and snippets.

@rakisaionji
Forked from develpudu/example.js
Created August 22, 2025 06:57
Show Gist options
  • Select an option

  • Save rakisaionji/c275db54edbffb94fbcc5ac4f8ff0c4d to your computer and use it in GitHub Desktop.

Select an option

Save rakisaionji/c275db54edbffb94fbcc5ac4f8ff0c4d to your computer and use it in GitHub Desktop.
NodeJS: How to run a process (also a shell script etc) on background separated with the parent node process.
const spawn = require('child_process').spawn;
// a command you want to execute.
const command = "node cli/hoge.js --aaa --bbb=123";
const parts = command.split(" ");
const cmd = parts[0];
const args = parts.splice(1);
// detached: true: This option makes the child process a leader of a new process group, allowing it to continue running after the parent process exits.
// stdio: 'ignore': This detaches the child process's input/output streams from the parent, preventing it from being affected by the parent's termination.
// child.unref(): This removes the parent's event loop reference to the child process, ensuring that the parent can exit independently.
spawn(cmd, args, {
stdio: 'ignore', // piping all stdio to /dev/null
detached: true,
env: process.env,
}).unref();
const { spawn } = require('child_process');
const child = spawn('node', ['background_script.js'], {
detached: true,
stdio: 'ignore',
});
child.unref();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment