2014-03-25 135 views
28

我有一个名为compile.js的独立Node脚本。它坐在小型快速应用程序的主文件夹内。如何从另一个Node.js脚本中运行Node.js脚本

有时我会从命令行运行compile.js脚本。在其他情况下,我希望它由Express应用程序执行。

这两个脚本都从package.json加载配置数据。 Compile.js目前不导出任何方法。

加载此文件并执行它的最佳方式是什么?我曾看过eval(),vm.RunInNewContextrequire,但不确定什么是正确的方法。

感谢您的任何帮助!

+0

你是否考虑过var exec = require('child_process')。exec; exec('节点 /compile.js',...)? – huocp

+0

请问http://nodejs.org/api/process.html#process_process_execargv是否符合您的需求? –

+1

为什么不简单地要求()呢? – dandavis

回答

1

派生一个子进程可能是有用的,看到http://nodejs.org/api/child_process.html

从例如在链接:

var cp = require('child_process'); 

var n = cp.fork(__dirname + '/sub.js'); 

n.on('message', function(m) { 
    console.log('PARENT got message:', m); 
}); 

n.send({ hello: 'world' }); 

现在,子进程会是这样......也从例如:

process.on('message', function(m) { 
    console.log('CHILD got message:', m); 
}); 

process.send({ foo: 'bar' }); 

但做简单的任务,我认为创建一个模块,扩展events.EventEmitter类将做... http://nodejs.org/api/events.html

26

您可以使用子进程来运行脚本,并监听退出和错误事件以了解进程何时完成或出错(在某些情况下可能会导致退出事件未触发)。这种方法的优点是可以处理任何异步脚本,即使那些没有明确设计为可以作为子进程运行的异步脚本,比如您想要调用的第三方脚本。例如:

var childProcess = require('child_process'); 

function runScript(scriptPath, callback) { 

    // keep track of whether callback has been invoked to prevent multiple invocations 
    var invoked = false; 

    var process = childProcess.fork(scriptPath); 

    // listen for errors as they may prevent the exit event from firing 
    process.on('error', function (err) { 
     if (invoked) return; 
     invoked = true; 
     callback(err); 
    }); 

    // execute the callback once the process has finished running 
    process.on('exit', function (code) { 
     if (invoked) return; 
     invoked = true; 
     var err = code === 0 ? null : new Error('exit code ' + code); 
     callback(err); 
    }); 

} 

// Now we can run a script and invoke a callback when complete, e.g. 
runScript('./some-script.js', function (err) { 
    if (err) throw err; 
    console.log('finished running some-script.js'); 
}); 

注意,如果在安全问题可能存在的环境中运行第三方脚本,它可能是最好的沙盒VM上下文运行该脚本。

+0

非常感谢这段代码。 –

+1

如果你想添加参数到你调用的节点js脚本: var process = childProcess.fork(scriptPath,['arg1','arg2']); –

+0

@TylerDurden谢谢!这应该包含在答案中。 – NullDev