1

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.

1 Answer 1

3

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,
    }
  });
Sign up to request clarification or add additional context in comments.

1 Comment

Wow! THAT was my problem? 🤦‍♀️ Works perfectly after this fix. Thank you 🙏

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.