1

How can one retrieve an updated environment variable once a node script is already running?

Consider the following gulp task. How can you update the environment variable Z (i.e., from some other script running on the system) so that the function outputs different values after it's running?

As is, environment variables set elsewhere are ignored and the function always outputs 'undefined'.

gulp.task('z', function () {
    var z;
    setInterval(function(){
        z = process.env.Z;
        console.log('Value of Z is: ' + z);
    }, 1000);

});

Running Windows 7. I have tried both set and setx but nothing will persist into the running node script. I wouldn't think this is possible since you generally can't pass environment variables between command prompts without re-launching them (and using setx). But then again SO users are special and I've been surprised before. Is this even possible?

JoshuaDavid
  • 8,861
  • 8
  • 47
  • 55

1 Answers1

2

Yes it's possible. There are many options actually. You can pass variables between multiple scripts with 'inter process communication (IPC)'...

The easyest option is probably to do it via sockets, ie with use of redis. Advantage of this is that you can also use it to communicate between processes running on different devices, if this would be required in the future.

Another option is to do it via the built in process signalling: https://nodejs.org/api/process.html#process_signal_events

There are many other options/library's with each their pro's and cons. For scalability you are probably best of when you do the communication via sockets, If performance is very important you can choose for an option which uses shared memory.

In this question are multiple options discussed; What's the most efficient node.js inter-process communication library/method?

Community
  • 1
  • 1
Sander
  • 171
  • 1
  • 10
  • For some reason I hadn't considered IPC, I was hung up on creating a simple flag polling mechanism through env variables. I ended up using zmq (zeromq) which is as simple as I could imagine in node. Thx! – JoshuaDavid Dec 22 '15 at 06:54