Search code examples
javascriptlinuxnode.jsdeb

How can I install a linux service from the service itself?


I'm not a specialist in Linux, so sorry if my terminology is not 100% correct. I have an embedded device running Debian. The device runs the Node.js webserver. This Node.js application is bundled together with the Node executable and packaged as a .deb file. The package defines a service (daemon?) by including init.d script. So in order to update the application I only have to type "dpkg -i my-service.deb". The Node.js application can upload debian packages (.deb) and store them in a temp folder.

The question: how can I update the service (node executable + node application) from within the node application itself?

... if I call child_process.exec("dpkg -i new-version-of-my-service.deb") it first stops the service and then nothing happens.


Solution

  • Here is how the problem was solved:

    function update_self(deb_package_filename) {
        var fileToInstall = path.join(upload_dir, deb_package_filename);
        var out = fs.openSync(path.join(upload_dir, 'out.log'), 'a');
        var err = fs.openSync(path.join(upload_dir, 'out.log'), 'a');
        var child = spawn("dpkg", ["-i", fileToInstall], {
            cwd: upload_dir,               // working directory
            detached: true,                // detach from the parent process group
            stdio: [ 'ignore', out, err ]
        });
        child.unref();
    }
    

    The child process is detached from the caller and therefore even when the parent process gets killed the dpkg process still runs.