How can I run multiple npm scripts in parallel?

后端 未结 22 2172
灰色年华
灰色年华 2020-11-22 05:48

In my package.json I have these two scripts:

  \"scripts\": {
    \"start-watch\": \"nodemon run-babel index.js\",
    \"wp-server\": \"webpack-         


        
22条回答
  •  -上瘾入骨i
    2020-11-22 06:22

    How about forking

    Another option to run multiple Node scripts is with a single Node script, which can fork many others. Forking is supported natively in Node, so it adds no dependencies and is cross-platform.


    Minimal example

    This would just run the scripts as-is and assume they're located in the parent script's directory.

    // fork-minimal.js - run with: node fork-minimal.js
    
    const childProcess = require('child_process');
    
    let scripts = ['some-script.js', 'some-other-script.js'];
    scripts.forEach(script => childProcess.fork(script));
    

    Verbose example

    This would run the scripts with arguments and configured by the many available options.

    // fork-verbose.js - run with: node fork-verbose.js
    
    const childProcess = require('child_process');
    
    let scripts = [
        {
            path: 'some-script.js',
            args: ['-some_arg', '/some_other_arg'],
            options: {cwd: './', env: {NODE_ENV: 'development'}}
        },    
        {
            path: 'some-other-script.js',
            args: ['-another_arg', '/yet_other_arg'],
            options: {cwd: '/some/where/else', env: {NODE_ENV: 'development'}}
        }
    ];
    
    let runningScripts= [];
    
    scripts.forEach(script => {
        let runningScript = childProcess.fork(script.path, script.args, script.options);
    
       // Optionally attach event listeners to the script
       runningScript.on('close', () => console.log('Time to die...'))
    
        runningScripts.push(runningScript); // Keep a reference to the script for later use
    });
    

    Communicating with forked scripts

    Forking also has the added benefit that the parent script can receive events from the forked child processes as well as send back. A common example is for the parent script to kill its forked children.

     runningScripts.forEach(runningScript => runningScript.kill());
    

    For more available events and methods see the ChildProcess documentation

提交回复
热议问题