Thursday, 15 September 2016

Right way to set env variable while exec or execFile in nodejs

According to the official documentation, exec allows you to pass additional environment variables as part of options like this:

This looks fine right? except that it totally isn't! By passing "env" as an option, you are not adding on to existing environment variables, but you are replacing it.  This is not clear from the documentation and can leave you scratching your head for a while as it can seem to break the command for no particular reason at all! So, you need to essentially make a copy of process.env and modify it like follows.

Thanks for stopping by!