PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 21, 2022

[FIXED] How to set Node Environment as Env Variable in the middle of the app?

 August 21, 2022     environment-variables, javascript, node.js, testing     No comments   

Issue

I know that I can do process.env.NODE_ENV = TEST but it is not working for me. Relevant code below:

test.js

import server from "../../src/index.js";

process.env.NODE_ENV = "test";
console.log(process.env.NODE_ENV);  // returns "test"
chai.use(chaiHttp);

// calls server here with chai-http

src/index.js

import express from "express";
import dotenv from "dotenv";

dotenv.config();

const app = express();

// Some API endpoint here that calls getUserFromUserId

app.listen(port, () => {
  logger.info(`App running on http://localhost:${port}`);
});

export default app;

user.js

console.log(process.env.NODE_ENV)  // returns undefined
process.env.NODE_ENV = "test"  // manually sets it here again
console.log(process.env.NODE_ENV)  // returns test correcly this time

So the issue here is that when I run test.js, I am importing, and therefore running user.js before I set my NODE_ENV. Since imports are hoisted I can't bring the env setting earlier either. However, I need the user.js to behave differently when I am testing, and hence I need to set the NODE_ENV before running user.js code. How can I achieve that?

Edit: I tried changing my test script to 'test: SET NODE_ENV=test && mocha'. This seems to set the node env but I am still facing issue.

user.js

console.log(process.env.NODE_ENV);  // returns test
console.log(process.env.NODE_ENV === "test");  // returns false
process.env.NODE_ENV = "test";
console.log(process.env.NODE_ENV);  // returns test
console.log(process.env.NODE_ENV === "test");  // returns true

Somehow the 2 'test' are different? There is also the issue of SET being Windows-specific.


Solution

For now I have settled with installing cross-env and doing

"test" : "cross-env NODE_ENV=test mocha"

but would love to hear better suggestions.



Answered By - Samson
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing