Let NodeJS application update itself using NPM

Viewed 4737

Hej There,

I'm trying to add some non-conventional functionality to my NodeJS application but I'm having some trouble. What I'm trying to do is the following:

I want to update my server code from the client. (An auto-update functionality if you will.)

My first attempt was to utilize the NPM API and run:

 npm.commands.install([package], function(err, data)

But of course this results in an error telling me NPM can not install while the server is running.

My second attempt was spawning NPM update using the following code:

  spawnProcess('npm', ['update'], { cwd: projectPath }, done);

The spawnProcess function is a generic spawn function:

var projectPath = path.resolve(process.cwd());
var spawnProcess = function(command, args, options, callback) {
    var spawn = require('child_process').spawn;
    var process = spawn(command, args, options);
    var err = false;

    process.stdout.on('data', function(data) {
        console.log('stdout', data.toString());
    });

    process.stderr.on('data', function(data) {
        err = true;
        console.log('stderr', data.toString());
    });

    if (typeof callback === 'function') {
        process.on('exit', function() {
            if (!err) {
                return callback();
            }
        });
    }
};

But this gives me a stderr followed by a 'CreateProcessW: can not find file' error. I don't quite know what I'm doing wrong.

If all else fails I thought it might be possible to write a shellscript killing Node, updating the application and then rebooting it. Something like:

kill -9 45728
npm update
node server

But I don't know if this is a plausible solution and how I would go about executing it from my node server. I'd rather have the spawn function working of course.

Any help is welcome. Thanks in advance!

3 Answers
Related