-
-
Save develpudu/88d364726226d8edf5cfc1f91a223ba3 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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