0

I am new to Node js, started developing the Angular application using Angular 1.2 and Node js. As of now, I have hardcoded the REST API(Java) endpoints in the node services.js. Now I want to load the base endpoint URI specific to the environment. I have tried few ways by setting a new key value for the process.env, a env file and load it. Can anyone please help me.

I have tried below approach.

Created devEnv.env file under root folder.

Added 3 key-value pairs

hostname = xyz
apikey = 123
devUrl = xyz/xyz/xyz.com/

Then in terminal, I am trying to add it to the source.

$ source denEnv.env

I am getting source not found.

Another way I have added the script in package.json file

{
  "start-dev": "source devEnv.env; node server.js"
}

In terminal I executed

$ npm start-dev

It's also failing. Can anyone please let me know what mistake I am doing and what is the correct approach.

Thanks in advance.

Kamal Chanda
  • 163
  • 2
  • 12

2 Answers2

1

There are three methods known to me:

1) .env file

You need to install dotenv package using npm install/yarn add and on top of your main file (e.g. index.js) put require('dotenv').config(). That should load your variables to node.

2) passed on a start

If you want pass a small amount of environmental variables you can try something like this in your package.json:

{
  "start-dev": "hostname=xyz apikey=123 devUrl=xyz/xyz/xyz.com node server.js"
}

Advice: environmental variables should look like HOSTNAME, API_KEY or DEV_URL.

3) system environmental variables

Solution: Set environment variables from file

Grzegorz Gajda
  • 2,424
  • 2
  • 15
  • 23
  • Thanks for the information. I have tried the first approach and its working. I even tried with env2 package and working fine. Thanks again – Kamal Chanda Jan 30 '18 at 23:09
0

Your variables are most likely not being exported to the shell. To be able to source your devEnv.env script, try to modify it as follows:

#!/bin/bash

export hostname=xyz
export apikey=123
export devUrl=xyz/xyz/xyz.com/

You most likely need to give it executable rights:

chmod +x devEnv.env

And then source it by running:

. devEnv.env

Another example can be found here: Set environment variables from file

TheBeardedOne
  • 292
  • 3
  • 6