Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Node Environment Variables in Jade file

I am trying to figure out how to optionally display text in a jade file based on the environment. I can't seem to figure out how to access the NODE_ENV variable in my jade file.

In my index.jade file I am doing:

if process.env.NODE_ENV === 'development'
  h1 I am in development mode
else
  h1 I am not in development mode

The problem is that process.env.NODE_env is undefined.

When I try and do: h1 #{process.env} outside of the if statement, Jade outputs [Object Object] onto the page.

When I try and do: h1 #{process.env.NODE_ENV} outside of the if statement, Jade does not output anything onto the page.

I am not rendering my Jade files on fly, rather I am building them all as "static" files whenever I start the server.

like image 920
Rastalamm Avatar asked May 20 '16 19:05

Rastalamm


People also ask

How do I see node environment variables?

If you have defined NODE_ENV variable then you should be able to see this by typing node in the command prompt which will open the node cell and then type process. env. NODE_ENV .

Where are node environment variables stored?

Environment variables are stored in your system shell that you start node. js from. They are a shell feature that node. js can read/modify.

How do I manage environment variables in node JS?

If you have multiple environment variables in your node project, you can also create an . env file in the root directory of your project, and then use the dotenv package to load them during runtime. You can also run your js file with node -r dotenv/config index.


1 Answers

Anything you want to access in the jade template has to be in the locals object sent down from the server. For something like the process environment, you can do this right when you fire up your app:

const express = require('express');
var app = express();

app.locals.env = process.env;  // though you might prefer to clone this instead of setting them equal

Then in your jade template you can do

#{env.NODE_ENV}

UPDATE

Adding for direct use, rather than in an express server.

const pug = require('pug');

// Compile the source code
const compiledFunction = pug.compileFile('template.pug');

// Render a set of data
console.log(compiledFunction(process.env));

That'll log it, but of course you could just as easily write that to an HTML file using fs utilities instead.

like image 199
Paul Avatar answered Oct 20 '22 07:10

Paul