Search code examples
javascriptnode.jsprocessrestart

How can I restart a Node.js child process


I'm trying to restart a certain child_process by the name of serverSpawnProcess. I can get it to stop, but I can't start it again.

serverSpawnProcess.stdin.write('stop\n');
serverSpawnProcess = null;
setTimeout(function() {
  serverSpawnProcess = spawn('java', [
    '-Xmx512M',
    '-Xms512M',
    '-jar',
    'server_files/minecraft_server.jar',
    'nogui'
  ]);
  response.send('r');
}, 10000);

is how I thought I'd go about it, but it only stops the server, it won't spawn it again. Node.js 5.3.0 if that helps.

EDIT For the sake of anyone else looking for how to do this, I ended up putting the spawn into a function, which I call like so

serverSpawnProcess.on("close", function() {
    response.send('r2');
    // Wait for process to exit, then run again

    startServer();
 });

Solution

  • So my guess is after 10 seconds timeout your minecraft server is still running (according to docs it saves some data to disk and stuff) and when you try to run another instance it fails due to port still being used.

    Try it like this:

    serverSpawnProcess.stdin.write('stop\n');
    serverSpawnProcess.on("close", function() {
        // Wait for process to exit, then run again
    
        serverSpawnProcess = spawn('java', [
            '-Xmx512M',
            '-Xms512M',
            '-jar',
            'server_files/minecraft_server.jar',
            'nogui'
        ]);
    });
    

    Also as https://stackoverflow.com/users/1139700/ross suggests, add a listener to error event so you know exactly what your problem is.

    serverSpawnProcess.on("error", function(err) {
        // ugh, something went wrong
        console.log("Server error:", err);
    });