Node.js - spawned process is generating error “exe

2019-07-14 19:44发布

问题:

I have the following code that's intended to spawn and detach a child process, which is just another node.js script in the same directory. Here's the exact code I'm running:

var fs = require('fs');
var child = require('child_process');

var out = fs.openSync('/tmp/daemon.log', 'a');
var options = {
    cwd: process.cwd(),
    env: process.env,
    detached: true,
    stdio: ['ignore', out, process.stderr]
};

child.spawn('/usr/local/bin/node ./daemon.js', [], options).unref();

All daemon.js does right now is exit after a timeout of two seconds:

setTimeout(function() {
    console.log('done');
}, 2000);

If I run daemon.js directly from the terminal it works as expected. If I run the same command being passed to child.spawn() it works as expected. However when I run the script it generates this error:

execvp(): No such file or directory

It doesn't seem node.js specific and I'm having trouble working out what the problem is. Does anybody have any suggestions?

For reference, this is on OS X 10.8.5 Server with node installed using Homebrew at path /usr/local/Cellar/node/0.10.25/bin/node and symlinked to /usr/local/bin/node.

EDIT

The code now works perfectly, with the added avdantage of it not mattering which working-directory the main script is run from!

var fs = require('fs');
var child = require('child_process');

var out = fs.openSync('/tmp/daemon.log', 'a');
var options = {
    cwd: process.cwd(),
    env: process.env,
    detached: true,
    stdio: ['ignore', out, process.stderr]
};

child.spawn('/usr/local/bin/node', [__dirname + '/daemon.js'], options).unref();

回答1:

Try changing

child.spawn('/usr/local/bin/node ./daemon.js', [], options).unref();

To:

child.spawn('/usr/local/bin/node', ['./daemon.js'], options).unref();

Or:

child.spawn('node', ['daemon.js'], options).unref();


回答2:

Instead try

__dirname+'/daemon.js'