How can I restart a Node.js app from within itself (programmatically)?

后端 未结 5 2295
余生分开走
余生分开走 2020-12-15 06:14

How can I create an app that can restart itself? I want to create an app that sets up a web-admin which can restart itself. Is this possible? If so, how? I was thinking this

相关标签:
5条回答
  • 2020-12-15 06:23

    Yes, upstart will restart your process without a nodemon.

    npm install -g nodemon
    sudo nodemon server.js
    

    nodemon will watch the files in the directory that nodemon was started, and if they change, it will automatically restart your node application.

    0 讨论(0)
  • 2020-12-15 06:25

    LK"I

    It is possible without external dependencies:

    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);
    

    source : https://gist.github.com/silverwind/d0802f7a919ae86ff25e

    0 讨论(0)
  • 2020-12-15 06:28

    I have run Forever several times and it is easy to get started with. Check it out at: https://github.com/nodejitsu/forever

    0 讨论(0)
  • 2020-12-15 06:42
    1. you can run your app using child process and manipulate it how needed: https://nodejs.org/api/child_process.html

    2. use forever, pm2 or whatever thing to restart after death and kill itself with process.exit() https://nodejs.org/api/process.html

    0 讨论(0)
  • 2020-12-15 06:44

    I know it's a little late to reply however I had a similar requirement. I wanted to restart my node process whenever I made a configuration change. I'm using pm2 to manage my node processes so it turned out to be really easy.

    After making a configuration change, i execute process.exit() from within the node process. As far as I can see, the process exits then pm2 restarts the process fine.

    Not sure yet if there are any side effects but it seems to be working fine for me right now.

    0 讨论(0)
提交回复
热议问题