How can I set NODE_ENV=production on Windows? - node.js

In Ubuntu it's quite simple; I can run the application using:
$ NODE_ENV=production node myapp/app.js
However, this doesn't work on Windows. Is there a configuration file where I can set the attribute?

Current versions of Windows use Powershell as the default shell, so use:
$env:NODE_ENV="production"
Per #jsalonen's answer below. If you're in CMD (which is no longer maintained), use
set NODE_ENV=production
This should be executed in the command prompt where you intend to run your Node.js application.
The above line would set the environment variable NODE_ENV for the command prompt where you execute the command.
To set environment variables globally so they persist beyond just the single command prompt, you can find the tool from System in Control Panel (or by typing 'environment' into the search box in the start menu).

I just found a nice Node.js package that can help a lot to define environment variables using a unique syntax, cross platform.
https://www.npmjs.com/package/cross-env
It allow you to write something like this:
cross-env NODE_ENV=production my-command
Which is pretty convenient! No Windows or Unix specific commands any more!

In PowerShell:
$env:NODE_ENV="production"

It would be ideal if you could set parameters on the same line as your call to start Node.js on Windows. Look at the following carefully, and run it exactly as stated:
You have these two options:
At the command line:
set NODE_ENV=production&&npm start
or
set NODE_ENV=production&&node index.js
The trick for it to work on Windows is you need to remove the whitespace before and after the "&&". Configured your package.json file with start_windows (see below) below. Then Run "npm run start_windows" at the command line.
//package.json
"scripts": {
"start": "node index.js"
"start_windows": "set NODE_ENV=production&&node index.js"
}

You can use
npm run env NODE_ENV=production
It is probably the best way to do it, because it's compatible on both Windows and Unix.
From the npm run-script documentation:
The env script is a special built-in command that can be used to list environment variables that will be available to the script at runtime. If an "env" command is defined in your package it will take precedence over the built-in.

I wrote a module win-node-env with which you can run your command just like you would in *nix.
NODE_ENV=production node myapp/app.js
It works by creating a NODE_ENV.cmd that sets the NODE_ENV environment variable and spawns a child process with the rest of the command and its args.
Just install it (globally), and run your npm script commands, it should automatically make them work.
npm install -g win-node-env

My experience using Node.js on Windows 7 64-bit in Visual Studio 2013 is that you need to use
setx NODE_ENV development
from a cmd window. AND you have to restart Visual Studio in order for the new value to be recognized.
The set syntax only lasts for the duration of the cmd window in which it is set.
Simple test in Node.js:
console.log('process.env.NODE_ENV = ' + process.env.NODE_ENV);
It returns 'undefined' when using set, and it will return 'development' if using setx and restarting Visual Studio.

If you are using Visual Studio with NTVS, you can set the environment variables on the project properties page:
As you can see, the Configuration and Platform dropdowns are disabled (I haven't looked too far into why this is), but if you edit your .njsproj file as follows:
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DebugSymbols>true</DebugSymbols>
<Environment>NODE_ENV=development</Environment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<DebugSymbols>true</DebugSymbols>
<Environment>NODE_ENV=production</Environment>
</PropertyGroup>
The 'Debug / Release' dropdown will then control how the variable is set before starting Node.js.

Here is the non-command line method:
In Windows 7 or 10, type environment into the start menu search box, and select Edit the system environment variables.
Alternatively, navigate to Control Panel\System and Security\System, and click Advanced system settings
This should open up the System properties dialog box with the Advanced tab selected. At the bottom, you will see an Environment Variables... button. Click this.
The Environment Variables Dialog Box will open.
At the bottom, under System variables, select New...This will open the New System Variable dialog box.
Enter the variable name and value, and click OK.
You will need to close all cmd prompts and restart your server for the new variable to be available to process.env. If it still doesn't show up, restart your machine.

To run your application in PowerShell (since && is disallowed):
($env:NODE_ENV="production") -and (node myapp/app.js)
Note that the text output of what the server's doing is suppressed, and I am not sure if that's fixable. (Expanding on #jsalonen's answer.)

Just to clarify, and for anyone else that may be pulling their hair out...
If you are using git bash on Windows, set node_env=production&& node whatever.js does not seem to work. Instead, use the native cmd. Then, using set node_env=production&& node whatever.jsworks as expected.
My use case:
I develop on Windows because my workflow is a lot faster, but I needed to make sure that my application's development-specific middleware were not firing in the production environment.

if you are using vs code terminal you have to use this command
$env:NODE_ENV="production"

first in powershell type
$env:NODE_ENV="production"
then type
node fileName.js
It will work perfectly displaying all the outputs.

For Windows
set NODE_ENV=development && react-scripts start
For Ubuntu, Linux, macOs
NODE_ENV=development react-scripts start

In case you are using GITBASH terminal
"set NODE_ENV=production"
will not work, what can you do is type
"export NODE_ENV=production"

For multiple environment variables, an .env file is more convenient:
# .env.example, committed to repo
DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3
# .env, private, .gitignore it
DB_HOST=real-hostname.example.com
DB_USER=real-user-name
DB_PASS=REAL_PASSWORD
It's easy to use with dotenv-safe:
Install with npm install --save-dev dotenv-safe.
Include it in your code (best at the start of the index.js) and directly use it with the process.env command:
require('dotenv').load()
console.log(process.env.DB_HOST)
Don't forget to ignore the .env file in your VCS.
Your program then fails fast if a variable "defined" in .env.example is unset either as an environment variable or in .env.

Restart VS code if the NODE_ENV or any other environment variable is not providing correct value. This should work after restart.

this will not set a variable but it's usefull in many cases. I will not recommend using this for production, but it should be okay if you're playing around with npm.
npm install --production

I used npm script for running a gulp task without "&&"
NODE_ENV=testcases npm run seed-db

set NODE_ENV=production & node server.js

Finally, the best method I could see is as follows.
"set-env-qa": "npm run env APP_ENV=qa",
"start:qa": "npm run set-env-qa && react-native start",
This will make sure we get the correct env setup for the programs. replace react-native-start with whichever next command you want.

In Windows 10 I have used $env:NODE_ENV="Production"
This worked on my vscode terminal. But if your server is listening first need to stop and set your env variable and start the app again. This way it worked for me.

If you are looking to set environment variable and run npm script in the same line then use:
$env:BASE_URL="https://example.com"; npm run __your_npm_script__

It seems that
{
"start_windows": "set NODE_ENV=test"
}
is not working for me. I'm currently trying this on my Windows machine. When I hit:
npm run start_windows
it would execute on the console without errors but when I try to echo
echo %NODE_ENV%
nothing comes out of it, meaning it does not exist and it wasn't set at all...

Related

SET: not found NODE JS

I use SET NODE_ENV=PRODUCTION& nodemon server.js in my package.json file.
But the environment not change and still run in the development mode.
It also throw error like sh: 1: SET: not found in terminal.
Since you're using sh and terminal, I'm guessing you're on either Mac or Linux, as most production servers are UNIX based. The correct command would be just NODE_ENV=PRODUCTION
Set works only windows OS. If you used Unix like Operating systems you should just make NODE_ENV=production

Cannot start npm serve on MacOS, IntelliJ ultimate on vuejs project

I am failing to start npm serve at Run/Debug Configuration in IntelliJ.
But doing it separately in Terminal within IntelliJ or on plain console works.
What's going on? How to solve that?
Here's what the Run console shows:
/usr/local/bin/node /usr/local/lib/node_modules/npm/bin/npm-cli.js run serve --scripts-prepend-node-path=auto
> pwdstorage#0.1.0 serve
> node_modules/.bin/vue-cli-service serve
env: node: No such file or directory
Process finished with exit code 127
As mentioned before running the command
/usr/local/bin/node /usr/local/lib/node_modules/npm/bin/npm-cli.js run serve --scripts-prepend-node-path=auto
on a terminal will properly work; even in IntelliJ.
At IntelliJ/Preferences.../Languages & Frameworks/Node.js and NPM the Node interpreter is set to /usr/local/bin/node and the Package manager is set to /usr/local/lib/node_modules/npm They both do exist.
What the frag is going on?
I would love to get a deeper understanding of the whole thing and do appreciate any inseide views on this.
The issue is that node is not on your $PATH; on MacOSX the environment variables differ between GUI applications and within the terminal. Terminal environment is only available to applications started from terminal.
To solve this problem, IDEA tries to load terminal environment by executing some scripts on startup, but it seems that it can't retrieve all needed stuff in your case - thus the issue. As a workaround, you can try starting IDEA from terminal.
Some links you may find useful: http://apple.stackexchange.com/questions/106355/setting-the-system-wide-path-environment-variable-in-mavericks, http://apple.stackexchange.com/questions/51677/how-to-set-path-for-finder-launched-applications.. The problem is that the way to define system-wide environment variables on Mac changes from one version to another (even minor system updates may break your environment)
As lena answered, it did help. Thank you for your help!
Starting it from the terminal does the job.
In my case I build a starter script
#! /bin/bash
/Applications/IntelliJ\ IDEA.app/Contents/MacOS/idea &
I am running the ultimate version of IntelliJ. The CE version does have another path to start!
The next two nice things to have would be
to have the opened terminal window automatically closed
link it with a proper icon placed on the desktop.
If anyone can help, go ahead!-)

How to run NodeJS CLI tools without having to type npx

TL;DR
I cannot execute commands such as tsc unless I include npx before it (e.g npx tsc). How can I fix this?
The title is a bad explanation of the problem I have.
Say I have installed an npm package with a CLI with it (typescript in this example). And the CLI is used like
tsc <filename> or just tsc. But whenever I try to do it like that, I get an error like
'tsc' is not recognized as an internal or external command,
operable program or batch file.
But... when I do
npx tsc
then it works!
So whats the problem?
The problem with doing npx tsc is because
npx is slow at executing commands
its annoying having to type npx and the front of every command.
And the thing is, this was originally not a problem with WSL.
Why dont you just use WSL?
I have always had problems with WSL (primarily permission issues due to security reasons) and so I uninstalled WSL and just used command prompt. I would have perferred using WSL but it was simply not an option.
Other Info:
I am using Windows command prompt.
I have installed the packages globally
So is there a way to just execute commands that way or is it Command prompts fault?
! this only works for Windows !
Ok, so I came across this post and thankfully, the first answer there was the solution!
Just add %USERPROFILE%\AppData\Roaming\npm to the path variable in system variables!
To access the system variables, press the Windows key, type Environment variables and click on Environment variables at the bottom of the window. The path variable can be found under User variables for (profile name).

Npm command not found in visual studio code

Please tell me how i can solve it. Iam using window 7 32 bit:
By default, Visual Studio Code runs shell commands like npm in a loginless shell. If you installed NVM, Visual Studio Code may have no indication where to find npm to run it.
Put the following lines are in .bash_profile: (Note: Not .bashrc.)
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion
Add this setting to settings.json:
"terminal.integrated.shellArgs.linux": ["-l"]
On Mac OS , I switched to the zsh and got this fixed. These following steps fixed the issue :
On your VsCode in Mac : shift + command + P .
On the Prompt > type : Terminal: Select Default Profile , then "Click it". Note, as you type you will find this option in the auto-complete .
Click the option for zsh or your desired shell.
Restart VSCode .
now npm will work in your vscode terminal.
I too had this issue.
To solve this follow the below steps.
Make sure you have npm installed
- go to command prompt & type npm -v
- if a version comes out it's installed, else go to https://nodejs.org/en/ and download same.
Then come to vs code and set deafult shell to cmd.
to do so,
- Press Ctrl+Shift+P and type Select Default Shell
- Select Command Prompt.
- Press Ctrl+`
- Type npm -v and see npm works. :)
I got this error after having just installed nodejs/npm, and the way i resolved, while still being able to use git bash terminal in vscode was to simply restart my computer (I hadn't done this after node installation).
I needed to kill the terminal in VS Code and restart a new terminal to get npm to show as installed.
As you're aware, you can configure your environment variables in windows at 2 levels.
At user level
At system level
When VS code is started, it picks the variables in path at a user level and not at system level because you haven't run the application as Administrator.
Just copy-paste your node path from System Variables to User Variables
This does the trick for windows.
Thanks.
If you just installed your node while your VScode was running. Restart your vscode it should start working.
You need to install npm first, https://www.npmjs.com/get-npm and make sure npm command is accessible using terminal/command prompt.
You can also use https://marketplace.visualstudio.com/items?itemName=eg2.vscode-npm-script This extension supports running npm scripts defined in the package.json file and validating the installed modules against the dependencies defined in the package.json.
On mac, I switched the default shell from bash to zsh and it fixed the issue.
I'm gonna add an answer just for help others because this question is 2 years old.
If you can run the npm start (NPM SCRIPTS below the Explorer view) but you are not able to launch the command with a shortcut: Then check npm extension is installed and/or enabled for the current workspace/folder.
Otherwise vsCode will not be able to run the script and you're going to get a message in a little box like this
command 'npm-script.start' not found
Maybe the NPM Scripts View below the explorer is not available without the plugin I'm not sure
For me, restarting VS code and even my PC didn't work, but after restarting VS code via "reload" (not restart, not refresh) from ctrl+shift+P, then in the top right of the terminal clicking the leftmost button and clicking "kill terminal" then restarting VS code it worked.
I had this issue too and I'm running QubesOS which uses virtualization.
I could manage to get it running until I'd a standalone VM.
That solved my problem.
Just mentioning for the ppl using virtualization like virtual box or VMware.

Running Bash Scripts and chaining commands in Powershell [duplicate]

In Ubuntu it's quite simple; I can run the application using:
$ NODE_ENV=production node myapp/app.js
However, this doesn't work on Windows. Is there a configuration file where I can set the attribute?
Current versions of Windows use Powershell as the default shell, so use:
$env:NODE_ENV="production"
Per #jsalonen's answer below. If you're in CMD (which is no longer maintained), use
set NODE_ENV=production
This should be executed in the command prompt where you intend to run your Node.js application.
The above line would set the environment variable NODE_ENV for the command prompt where you execute the command.
To set environment variables globally so they persist beyond just the single command prompt, you can find the tool from System in Control Panel (or by typing 'environment' into the search box in the start menu).
I just found a nice Node.js package that can help a lot to define environment variables using a unique syntax, cross platform.
https://www.npmjs.com/package/cross-env
It allow you to write something like this:
cross-env NODE_ENV=production my-command
Which is pretty convenient! No Windows or Unix specific commands any more!
In PowerShell:
$env:NODE_ENV="production"
It would be ideal if you could set parameters on the same line as your call to start Node.js on Windows. Look at the following carefully, and run it exactly as stated:
You have these two options:
At the command line:
set NODE_ENV=production&&npm start
or
set NODE_ENV=production&&node index.js
The trick for it to work on Windows is you need to remove the whitespace before and after the "&&". Configured your package.json file with start_windows (see below) below. Then Run "npm run start_windows" at the command line.
//package.json
"scripts": {
"start": "node index.js"
"start_windows": "set NODE_ENV=production&&node index.js"
}
You can use
npm run env NODE_ENV=production
It is probably the best way to do it, because it's compatible on both Windows and Unix.
From the npm run-script documentation:
The env script is a special built-in command that can be used to list environment variables that will be available to the script at runtime. If an "env" command is defined in your package it will take precedence over the built-in.
I wrote a module win-node-env with which you can run your command just like you would in *nix.
NODE_ENV=production node myapp/app.js
It works by creating a NODE_ENV.cmd that sets the NODE_ENV environment variable and spawns a child process with the rest of the command and its args.
Just install it (globally), and run your npm script commands, it should automatically make them work.
npm install -g win-node-env
My experience using Node.js on Windows 7 64-bit in Visual Studio 2013 is that you need to use
setx NODE_ENV development
from a cmd window. AND you have to restart Visual Studio in order for the new value to be recognized.
The set syntax only lasts for the duration of the cmd window in which it is set.
Simple test in Node.js:
console.log('process.env.NODE_ENV = ' + process.env.NODE_ENV);
It returns 'undefined' when using set, and it will return 'development' if using setx and restarting Visual Studio.
If you are using Visual Studio with NTVS, you can set the environment variables on the project properties page:
As you can see, the Configuration and Platform dropdowns are disabled (I haven't looked too far into why this is), but if you edit your .njsproj file as follows:
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DebugSymbols>true</DebugSymbols>
<Environment>NODE_ENV=development</Environment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<DebugSymbols>true</DebugSymbols>
<Environment>NODE_ENV=production</Environment>
</PropertyGroup>
The 'Debug / Release' dropdown will then control how the variable is set before starting Node.js.
Here is the non-command line method:
In Windows 7 or 10, type environment into the start menu search box, and select Edit the system environment variables.
Alternatively, navigate to Control Panel\System and Security\System, and click Advanced system settings
This should open up the System properties dialog box with the Advanced tab selected. At the bottom, you will see an Environment Variables... button. Click this.
The Environment Variables Dialog Box will open.
At the bottom, under System variables, select New...This will open the New System Variable dialog box.
Enter the variable name and value, and click OK.
You will need to close all cmd prompts and restart your server for the new variable to be available to process.env. If it still doesn't show up, restart your machine.
To run your application in PowerShell (since && is disallowed):
($env:NODE_ENV="production") -and (node myapp/app.js)
Note that the text output of what the server's doing is suppressed, and I am not sure if that's fixable. (Expanding on #jsalonen's answer.)
Just to clarify, and for anyone else that may be pulling their hair out...
If you are using git bash on Windows, set node_env=production&& node whatever.js does not seem to work. Instead, use the native cmd. Then, using set node_env=production&& node whatever.jsworks as expected.
My use case:
I develop on Windows because my workflow is a lot faster, but I needed to make sure that my application's development-specific middleware were not firing in the production environment.
if you are using vs code terminal you have to use this command
$env:NODE_ENV="production"
first in powershell type
$env:NODE_ENV="production"
then type
node fileName.js
It will work perfectly displaying all the outputs.
For Windows
set NODE_ENV=development && react-scripts start
For Ubuntu, Linux, macOs
NODE_ENV=development react-scripts start
In case you are using GITBASH terminal
"set NODE_ENV=production"
will not work, what can you do is type
"export NODE_ENV=production"
For multiple environment variables, an .env file is more convenient:
# .env.example, committed to repo
DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3
# .env, private, .gitignore it
DB_HOST=real-hostname.example.com
DB_USER=real-user-name
DB_PASS=REAL_PASSWORD
It's easy to use with dotenv-safe:
Install with npm install --save-dev dotenv-safe.
Include it in your code (best at the start of the index.js) and directly use it with the process.env command:
require('dotenv').load()
console.log(process.env.DB_HOST)
Don't forget to ignore the .env file in your VCS.
Your program then fails fast if a variable "defined" in .env.example is unset either as an environment variable or in .env.
Restart VS code if the NODE_ENV or any other environment variable is not providing correct value. This should work after restart.
this will not set a variable but it's usefull in many cases. I will not recommend using this for production, but it should be okay if you're playing around with npm.
npm install --production
I used npm script for running a gulp task without "&&"
NODE_ENV=testcases npm run seed-db
set NODE_ENV=production & node server.js
Finally, the best method I could see is as follows.
"set-env-qa": "npm run env APP_ENV=qa",
"start:qa": "npm run set-env-qa && react-native start",
This will make sure we get the correct env setup for the programs. replace react-native-start with whichever next command you want.
In Windows 10 I have used $env:NODE_ENV="Production"
This worked on my vscode terminal. But if your server is listening first need to stop and set your env variable and start the app again. This way it worked for me.
If you are looking to set environment variable and run npm script in the same line then use:
$env:BASE_URL="https://example.com"; npm run __your_npm_script__
It seems that
{
"start_windows": "set NODE_ENV=test"
}
is not working for me. I'm currently trying this on my Windows machine. When I hit:
npm run start_windows
it would execute on the console without errors but when I try to echo
echo %NODE_ENV%
nothing comes out of it, meaning it does not exist and it wasn't set at all...

Resources