Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js forever with environment variable

The command I run on my server to start my node app is:

sudo IS_PROD=1 node app.js 

I have forever installed but can't seem to pass in the environment variable.

sudo IS_PROD=1 forever node app.js 

Doesn't seem to do the trick. I have tried several varieties of this. How do I either execute this command successfully or permanently set the environment variable?

like image 672
user1168427 Avatar asked Jan 31 '13 03:01

user1168427


People also ask

Why do you use forever with node js?

Forever is an npm module that ensures a Node. js script continuously runs in the background on the server. It's a helpful CLI tool for the production environment because it helps manage the Node applications and their processes.

Do we need to set environment variables for node JS?

You really do not need to set up your own environment to start learning Node. js. Reason is very simple, we already have set up Node.

Does node JS run all the time?

NodeJS is a runtime environment on a V8 engine for executing JavaScript code with some additional functionality that allows the development of fast and scalable web applications but we can't run the Node. js application locally after closing the terminal or Application, to run the nodeJS application permanently.

What is .env node JS?

NODE_ENV is an environment variable that stands for node environment in express server. The NODE_ENV environment variable specifies the environment in which an application is running (usually, development or production).


2 Answers

First of all you should skip the node thing in you command, it should not be there, you should not be able to execute that. forever automatically starts your script using nodejs. Instead you should do like this;

sudo IS_PROD=1 forever app.js 

Probably you, instead of starting your server in foreground, will want to start your server as a daemon. eg.

sudo IS_PROD=1 forever start app.js 

This will create a process in the background that will watch your node app and restart it when it exits. For more information see the readme.

Both of these methods preserves the environment variables, just like when you are just using node.

like image 137
Mattias Avatar answered Sep 20 '22 17:09

Mattias


app.js:

console.log(process.env.IS_PROD); 

Using node (v0.8.21)

$ node app.js undefined  $ IS_PROD=1 node app.js 1  $ sudo IS_PROD=1 node app.js 1 

Using forever (v0.10.0)

$ forever app.js undefined  $ IS_PROD=1 forever app.js 1  $ sudo IS_PROD=1 forever app.js 1 

Documentation:

process.env

An object containing the user environment. See environ(7).

like image 31
mak Avatar answered Sep 16 '22 17:09

mak