Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

javascript - How do I run a Node.js script from within another Node.js script

I have a standalone Node script called compile.js. It is sitting inside the main folder of a small Express app.

Sometimes I will run the compile.js script from the command line. In other scenarios, I want it to be executed by the Express app.

Both scripts load config data from the package.json. Compile.js does not export any methods at this time.

What is the best way to load up this file and execute it? I have looked at eval(), vm.RunInNewContext, and require, but not sure what is the right approach.

Thanks for any help!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use a child process to run the script, and listen for exit and error events to know when the process is completed or errors out (which in some cases may result in the exit event not firing). This method has the advantage of working with any async script, even those that are not explicitly designed to be run as a child process, such as a third party script you would like to invoke. Example:

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');
});

Note that if running third-party scripts in an environment where security issues may exist, it may be preferable to run the script in a sandboxed vm context.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...