Chris Calo
Chris Calo

Reputation: 7838

Node.js: How to pass environment variables with a shell command?

I'm trying to generate specific values in a Node.js script and then pass them as environment variables to a shell command, but I can't seem to get it working. What's the right way to execute a string as a shell command from Node.js while passing in my own environment variables?

The following doesn't seem to be working as I would expect:

const shell = require("shelljs");
const { findPort } = require("./find-port");

async function main() {
  // imagine that `findPort(value)` starts at the provided `value` and
  // increments it until it finds an available port
  const PORT = await findPort(8000); // 8000, 8001, etc
  const DB_PORT = await findPort(3306); // 3306, 3307, etc

  shell.exec(`yarn run dev`, {
    env: {
      PORT,
      DB_PORT,
    },
    async: true,
  });
}

main();

When I try to run this, I get the following error:

env: node: No such file or directory

Important: I don't want any values to leak out of this specific script, which is why I'm trying to avoid the export FOO=bar syntax, but I may be misunderstanding how that works.

I'd prefer a solution that uses shelljs, but I'm open to other solutions that use child_process.exec, execa, etc.

Upvotes: 1

Views: 2978

Answers (1)

that other guy
that other guy

Reputation: 123550

The script does exactly what you ask for: it runs yarn run dev with your environment variables. Unfortunately, that means that it does not run with the system's environment variables that yarn depends on, like PATH.

You can instead run it with both your variables and the system's variables:

  shell.exec(`yarn run dev`, {
    env: {
      ...process.env,
      PORT,
      DB_PORT,
    }
  });

Upvotes: 3

Related Questions