Using spawn function with NODE_ENV=production

前端 未结 4 659
天命终不由人
天命终不由人 2021-02-02 07:42

I\'m currently trying to run process using spawn. What I am trying to run from shell is the following;

NODE_ENV=production node app/app.js

相关标签:
4条回答
  • 2021-02-02 08:00

    This worked for me

    var spawn = require('child_process').spawn;
    var productionEnv = Object.create(process.env);
    productionEnv.NODE_ENV = 'production';
    var start = spawn('node', ['app.js'], {env: productionEnv});
    

    this did not

    var spawn = require('child_process').spawn;
    var start = spawn('node', ['app.js'], {env: {NODE_ENV: 'production'}});
    
    0 讨论(0)
  • 2021-02-02 08:03

    Your usage of spawn is not correct:

    spawn( command, args, options ):

    Launches a new process with the given command, with command line arguments in args. If omitted, args defaults to an empty Array.

    The third argument is used to specify additional options, which defaults to:

    { cwd: undefined, env: process.env }

    Use env to specify environment variables that will be visible to the new process, the default is process.env.

    So the env variable NODE_ENV should be provided on the options argument:

    // ES6 Object spread eases extending process.env
    spawn( 'node', ['app.js'], { env: { ...process.env, NODE_ENV: 'test' } }})
    

    See also How do I debug "Error: spawn ENOENT" on node.js?

    0 讨论(0)
  • 2021-02-02 08:07

    Syntax: spawn(command, [args], [options])

    var spawn = require('child_process').spawn;
    var start = spawn('node', ['app.js'], {env: {NODE_ENV: 'production'}});
    

    Or keep default ENV variables:

    var spawn = require('child_process').spawn;
    
    var productionEnv = process.env; // TODO should clone process.env like utils.extend
    productionEnv.NODE_ENV = 'production';
    
    var start = spawn('node', ['app.js'], {env: productionEnv});
    

    My test:

    app.js

    console.log(process.env);
    

    spawn.js

    var spawn = require('child_process').spawn;
    var start = spawn('node', ['app.js'], {env: {NODE_ENV: 'production'}});
    
    start.stdout.pipe(process.stdout);
    

    from terminal:

    node spawn
    

    output:

    { NODE_ENV: 'production' }
    
    0 讨论(0)
  • 2021-02-02 08:10

    add shell option worked for me

    gulp.task('xxx', function (callback) {
        process.chdir('xxx/');
        var spawn = require('child_process').spawn;
        var productionEnv = Object.create(process.env);
        // var jekyll = spawn('gulp', ['stylecheck'], {stdio: 'inherit', env: productionEnv});
        var jekyll = spawn('gulp', ['stylecheck'], {stdio: 'inherit', env: productionEnv, shell: true});
    
        jekyll.on('exit', function (code) {
            console.log(arguments);
        });
    });
    
    0 讨论(0)
提交回复
热议问题