Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using spawn function with NODE_ENV=production

Tags:

node.js

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

Here's the code to run that;

var spawn = require('child_process').spawn; var start = spawn('NODE_ENV=production',['node','app/app.js']); 

However, I got the following error;

events.js:72         throw er; // Unhandled 'error' event               ^ Error: spawn ENOENT     at errnoException (child_process.js:980:11)     at Process.ChildProcess._handle.onexit (child_process.js:771:34) 

How can I do that using spawn ?

like image 614
aacanakin Avatar asked Dec 29 '13 12:12

aacanakin


People also ask

How do I use an env file in package JSON?

By using dotenv and cross-var together, we're able to read in whichever . env files we want, or consume existing environment variables (from cli, bash_profile, CI, etc) and then easily substitute them into our package. json scripts and it works across development platforms! Recreating the docker scripts in our package.

What does NODE_ENV default to?

We see that it in fact reads NODE_ENV and defaults to 'development' if it isn't set. This variable is exposed to applications via 'app.

What is process env NODE_ENV === development?

process. env is a reference to your environment, so you have to set the variable there. To set an environment variable in Windows: SET NODE_ENV=development. on macOS / OS X or Linux: export NODE_ENV=development. Follow this answer to receive notifications.

How is process env NODE_ENV works?

Node. js exposes the current process's environment variables to the script as an object called process. env. From there, the Express web server framework popularized using an environment variable called NODE_ENV as a flag to indicate whether the server should be running in “development” mode vs “production” mode.


1 Answers

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?

like image 98
laconbass Avatar answered Oct 13 '22 03:10

laconbass