0

I tried to share my global variable across js files and also in gulp task without using module.exports and require.

Here is the sample code:

File 1:

server.js

var server = new Hapi.Server()
  global.configurationManagerObj = 'Dev'

File 2:

siteconfig.js

console.log("This is global variable from server file",global.configurationManagerObj)

File 3:

gulpfile.js

gulp.task('setenv', function(done) {
    console.log("Global variable is shared in gulp task", global.configurationManagerObj);
    done();
});

But If I tried to get the variable it shows undefined.

Ramyachinna
  • 413
  • 1
  • 8
  • 20

3 Answers3

0

your can assign variable on global process object and can access it anywhere.

this might help read-environment-variables

Community
  • 1
  • 1
Fazal Rasel
  • 4,446
  • 2
  • 20
  • 31
  • Thanks Fazal.. it works when I use like this process.env.config = 'dev' but If I using it in gulp task it shows undefined why? – Ramyachinna Apr 18 '17 at 06:50
0

env variable is only available in Nodejs process .if node is not running u will not have the variable.and u cant get that variable outside the node process also. so better you use require i think ps: totally personal view.

Nilasis Sen
  • 299
  • 1
  • 10
0

Have you tried using environment variable to store global variables? process.env is build in to nodejs.

Ex. process.env.FOO = "foo"

You'll only be able to access it when the node process is running otherwise it will just show everything as undefined.

PS: Keep in mind that this is an anti pattern. Also, assigning a property on process.env will implicitly convert the value to a string.

saran3h
  • 12,353
  • 4
  • 42
  • 54