Home > database >  Node scripts resetting ENV variables between script commands
Node scripts resetting ENV variables between script commands

Time:10-01

I'm trying to set NODE_EXTRA_CA_CERTS in a node script like so:

// package.json
"scripts": {
    "load-cert": "export NODE_EXTRA_CA_CERTS=cert.pem",
    "start": "node main.js"
  },

npm run load-cert && npm run start

But that doesn't work (gives SSL error). Specifically, I think, because I'm loading the contract in its own separate script then running a different script/command.

This also doesn't work

"scripts": {
    "load-cert": "export NODE_EXTRA_CA_CERTS=riotgames.pem",
    "start": "npm run load-cert && node main.js"
  },

npm run start

The following script works:

"scripts": {
    "start": "export NODE_EXTRA_CA_CERTS=cert.pem && node main.js"
  },

npm run start

Weirdly enough, this also works:

"scripts": {
    "start": "node main.js",
    "load-cert-start": "export NODE_EXTRA_CA_CERTS=riotgames.pem && npm run start"
  },

npm run load-cert-start

Can anyone help me understand why this is happening and if there's a way I can have a script to just load the certificate?

CodePudding user response:

Setting an environment variable with export sets it for the current process and all child processes, but NOT the parent process. When you run npm run load-cert, that is a new child process of your shell. When you run npm run start, that is a different child process of your shell and is not a child process of the shell that exported the variable.

* Your shell
  \ * npm run load-cert {}
    \ * shell {NODE_EXTRA_CA_CERTS=riotgames.pem}
  \ * npm run load-cert {}

If you combine the two commands together, as in export NODE_EXTRA_CA_CERTS=cert.pem && node main.js, then the node process is a child process of the shell with the environment variable set:

* Your shell
  \ * npm run load-cert {}
    \ * shell {NODE_EXTRA_CA_CERTS=riotgames.pem}
      \ * node {NODE_EXTRA_CA_CERTS=riotgames.pem}

Or export NODE_EXTRA_CA_CERTS=riotgames.pem && npm run start

* Your shell
  \ * npm run load-cert {}
    \ * shell {NODE_EXTRA_CA_CERTS=riotgames.pem}
      \ * npm run start {NODE_EXTRA_CA_CERTS=riotgames.pem}
        \ * node {NODE_EXTRA_CA_CERTS=riotgames.pem}

And for npm run load-cert && node main.js

* Your shell
  \ * npm run start {}
    \ * shell started by npm
      \ * npm run load-cert {}
        \ * shell {NODE_EXTRA_CA_CERTS=riotgames.pem}
      \ * node {} <-- Sibling, not child, of npm run load-cert

(Note I omitted a couple of non-relevant processes in-between in these diagrams)

  • Related