Skip to content

Instantly share code, notes, and snippets.

@silverwind
Last active September 22, 2023 15:50
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save silverwind/d0802f7a919ae86ff25e to your computer and use it in GitHub Desktop.
Save silverwind/d0802f7a919ae86ff25e to your computer and use it in GitHub Desktop.
#!/usr/bin/env node
"use strict";
console.log("This is pid " + process.pid);
setTimeout(function () {
process.on("exit", function () {
require("child_process").spawn(process.argv.shift(), process.argv, {
cwd: process.cwd(),
detached : true,
stdio: "inherit"
});
});
process.exit();
}, 5000);
@joeycozza
Copy link

This was so helpful! It got me 99% of what I needed. I want to just comment my use case and how it differed a little bit in case it helps someone else. My script was to be run in the terminal and get input from the user. If they chose a certain option, I would do some work, and then need to restart the script so the work would be reflected correctly, but it would need to continue getting user input on the restarted process (which was the tricky part for me to get right).

It (getting user input from keyboard) finally started working as expected when I DIDN'T explicitly do a process.exit() after spawning the child process.

const inquirer = require('inquirer');
const childProcess = require('child_process');

inquirer.prompt([makePromptOptions('Hello There')])
.then(response => {
  if (response.answer === 'restart') {
    //perform some updating code here

    childProcess.spawn(process.argv.shift(), process.argv, {
      cwd: process.cwd(),
      detached: true,
      stdio: 'inherit'
    });
    // process.exit(0);  <-- doing a process.exit() here was messing up user input on the child_process. commenting it out make input work as expected.
  } else {
    console.log('Not doing the new process. Finishing here.');
  }
});

function makePromptOptions(message) {
  return {
    type: 'list',
    name: 'answer',
    message,
    choices: [
      {
        value: 'restart',
        name: 'Have this script automatically update and restart itself!'
      },
      {
        value: 'continue',
        name: 'Continue without updating'
      }
    ]
  };
}

@ozyman42
Copy link

ozyman42 commented Feb 5, 2019

I wonder if there could be a way to restart the process and have it still accept user input properly. It seems a bit sloppy to leave dead processes around doing nothing.

@sngrl
Copy link

sngrl commented Aug 25, 2021

Only this one solution allow helped me to prevent memory leak in nodejs, argh! Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment