1

I am writing a native addon for NodeJS. How can I use an environment variable as a constant at compile time? That is, "inject" a constant in to the NodeJS C++ addon from an environment variable set during node-gyp build or npm install. I found this answer, however as far as I can see, there is no equivalent option for passing through variables to node-gyp

Community
  • 1
  • 1
BenLanc
  • 2,344
  • 1
  • 19
  • 24
  • You can't. Variables aren't constant. Your question embodies a contradiction in terms. – user207421 Mar 28 '17 at 10:29
  • @EJP I wasn't asking how to make a variable constant (definitely a contradiction in terms), I'm asking how to define a constant at compile time – BenLanc Mar 28 '17 at 10:42

2 Answers2

3

I found that the defines block and variable expansion in binding.gyp will achieve what I'm after:

{
  "targets": [
    {
      "target_name": "targetName",
      "sources": [ "source.cc" ],
      "defines": [
        'MY_DEFINE="<!(echo $MY_ENV_VAR)"'
      ]
    }
  ]
}

Then MY_DEFINE is available with value equal to whatever MY_ENV_VAR set set to at compile time.

BenLanc
  • 2,344
  • 1
  • 19
  • 24
1

Normally when you create a Makefile yourself you can pass options to the compiler like:

-D name=definition

which is equivalent of having this in the source code:

#define name "definition"

so using:

-D NAME=$NAME

would put the NAME environment variable as a NAME constant in the compiled source code.

But with node-gyp the Makefile is generated for you, see:

You may need to change the generated Makefile after you run:

node-gyp configure

but before you run:

node-gyp build

or you can make a simple library which entire purpose would be to have a given value defined that would be used by your Node addon.

Another option would be to have a script that does something like:

echo "#define NAME \"$NAME\"" > config.h

and you can then include the config.h file by your Node native addon or any other code written in C or C++.

rsp
  • 107,747
  • 29
  • 201
  • 177