Jason Fingar
Jason Fingar

Reputation: 3372

Node Environmental variable on Windows

I noticed this strange behavior which is not a big deal, but bugging the heck out of me.

In my package.json file, under the "scripts" section, I have a "start" entry. It looks like this:

"scripts": {
    "start": "APPLICATION_ENV=development nodemon app.js"
}

typing npm start on a Mac terminal works fine, and nodemon runs the app with the correct APPLICATION_ENV variable as expected. When I try the same on a Windows environment, I get the following error:

"'APPLICATION_ENV' is not recognized as an internal or external command, operable program or batch file."

I have tried the git-bash shell and the normal Win CMD prompt, same deal.

I find this odd, because typing the command directly into the terminal (not going through the package.json script via npm start) works fine.

Has anyone else seen this and found a solution? Thanks!!

Upvotes: 1

Views: 3053

Answers (3)

ZhaoRachi
ZhaoRachi

Reputation: 89

You should use "set" command to set environment variables in Windows.

"scripts": {
    "start": "set APPLICATION_ENV=development && nodemon app.js"
}

Something like this.

Upvotes: 0

Jason Fingar
Jason Fingar

Reputation: 3372

I ended up using the dotenv package based on the 2nd answer here:

Node.js: Setting Environment Variables

I like this because it allows me to setup environmental variables without having to inject extra text into my npm script lines. Instead, they are using a .env file (which should be placed on each environment and ommitted from version control).

Upvotes: 1

RobC
RobC

Reputation: 24982

For cross-platform usage of environment variables in your scripts install and utilize cross-env.

"scripts": {
    "start": "cross-env APPLICATION_ENV=development nodemon app.js"
}

The issue is explained well at the link provided to cross-env. It reads:

Most Windows command prompts will choke when you set environment variables with NODE_ENV=production like that. (The exception is Bash on Windows, which uses native Bash.) Similarly, there's a difference in how windows and POSIX commands utilize environment variables. With POSIX, you use: $ENV_VAR and on windows you use %ENV_VAR%.

Upvotes: 3

Related Questions