Set environment variables in package.json - node.js

I've had a look at quite a number of answers to questions similar to mine but i've not been able to find a working solution for my use case yet.
I've got an environment variable of lets say auth=false. i'd like to set auth=true when i run a particular script in my package.json.
Script in package.json looks like this:
"dev-use-auth": "auth=true && npm run dev"
After running this script, process.env.auth is still set to false. I've also tried using the cross-env package with no luck

This, most likely, would depend on the OS, but for Linux environments you should get rid of the &&.
The && indicates that you wish to run the commands serially.
Try this, instead:
"dev-use-auth": "auth=true npm run dev"

it depends on the operative system you are working on, cross-env will help you running on multiple operative systems by calling it:
"dev-use-auth": "cross-env auth=true npm run dev"
on windows:
"dev-use-auth": "set auth=true && npm run dev"
on unix (mac, linux, etc..c)
"dev-use-auth": "auth=true npm run dev"

Related

The term 'NODE_ENV=development' is not recognized as the name of a cmdlet, function, script file, or operable program

I want to set some env variable in my node app but when I run this command NODE_ENV=development x=23 nodemon.cmd server.js then it gives me that error NODE_ENV=development' is not recognized, I found some solution where it said that I have to run a
npm package npm install -g win-node-env then it will work, but in my case, I got the same error. I am a windows user, any solution how to fix this.
This may or may not relevant to your question, but as far as I know, windows powershell syntax does not assign variable that way.
to assign variable in windows, you can subtitute NODE_ENV=development with $NODE_ENV:development
As a workaround, and if you want to run it on any OS, use cross-env npm package.
npm install --save-dev cross-env
Now, it can run command such as:
cross-env NODE_ENV=development node server.js

"npm run" commands fail on Windows

I am using Windows PowerShell ISE with administrator privileges. My project uses webpack, which is installed as a local dependency with npm. I have a "script" defined in package.json:
"build": "webpack --progress --config resources/assets/build/webpack.config.js",
When I execute npm run build I get the error message 'webpack' is not recognized as an internal or external command, but if I copy the webpack command and execute that it works fine. I'm not going to list my whole system PATH here, but it includes .\node_modules\.bin at the beginning. Clearly Windows has no problem finding webpack but Node for some reason can't.
I tried running npm run build in a privilege-less Command Line, no difference. I upgraded to the latest versions of Node and npm (13.0.1 and 6.12.1, respectively), to no avail. I even tried prefixing the command in package.json with ./node_modules/.bin/ but that didn't work.
Please don't suggest that I install webpack globally as that is not a real solution. Node is giving me this error with all locally-installed commands, not just webpack. I should be able to run commands locally through npm.
if you're using a recent version of npm, you can try
npx webpack ....
alternatively, you can install webpack locally and specify the exact path
node_modules/webpack/bin/webpack.js ....
In the end, I had to bite the bullet and install webpack globally.

Setting environment variables package.json in Windows 10

UPDATE: As it is explained in the question, this is not a duplicate because I have already tried adding the set keyword before the environment variable and that did not solve the problem.
I am in the process of learning node and typing examples from a book. The first examples deal with showing how the "http" module works and how to create a server to listen to requests. At some point the book asks to add the following line to the scripts section of the package.json file:
"server": "SERVERPORT=3002 node ./fiboserver"
When I try to run the example with npm run server I get the following error message:
'SERVERPORT' is not recognized as an internal or external command
I haven't been able to find any answer on the internet, at most I found that I could try:
"server": "set SERVERPORT=3002 node ./fiboserver"
But that doesn't help either, the only difference is that instead of the error message I get the command prompt again so apparently the server is never run.
I believe the author used a Linux machine, I am using a Windows 10 laptop.
I am really committed to learn Node and my line of work is on Windows environments. I believe that setting environment variables on package.json is important so I could really use some help in figuring this out.
Thank you.
Make it cross-platform by using cross-env:
"server": "cross-env SERVERPORT=3002 node ./fiboserver"
On Windows you have to separate the command of setting a variable from the one which runs the server with the && operator.
That being said, you have to do something like this:
"server": "set SERVERPORT=3002 && node ./fiboserver"
I've gone through the same problem and used one of the following methods.
Method 1
If I run (without using the npm wrapper script)
HOST=0.0.0.0 PORT=8000 ./node_modules/.bin/react-scripts start
it works fine. As Quentin says,
Must be something to do with how npm shells out then
To fix it, I've gone to package.json and changed the "start" script to
"start": "./node_modules/.bin/react-scripts start",
Then npm start works fine.
Method 2
Use the cross-env package.
For that install it using the following command
npm i cross-env
then go to package.json and change it to
"start": "cross-env ./node_modules/.bin/react-scripts start",
And then running npm start will also work fine:
You can set bash as package.json scripts runner and it's will work in windows and linux.
Just set it once:
for yarn yarn config set script-shell /bin/bash
for npm npm config set script-shell /bin/bash
Or "C:\\Program Files\\git\\bin\\bash.exe" instead /bin/bash
It's will allow you to run npm script cross-platform:
"server": "SERVERPORT=3002 node ./fiboserver"

Running npm scripts conditionally

I have 2 main build configurations - dev and prod.
I push updates to a heroku server that run npm install --production to install my app.
In the package.json I have the following segment:
"scripts": {
"postinstall": "make install"
}
that runs a make file that is responsible for uglifying the code and some other minor things.
However, I don't need to run this makefile in development mode. Is there any way to conditionally run scripts with npm?..
Thanks!
You can have something like this defined in your package.json (I'm sure theres a better shorthand for the if statement.)
"scripts": {
"postinstall":"if test \"$NODE_ENV\" = \"production\" ; then make install ; fi "
}
Then when you execute npm with production flag like you stated you already do
npm install --production
it will execute your make install because it will set $NODE_ENV = production
When I need to conditionally execute some task(s), I pass environment variables to the script/program and which takes care of that logic. I execute my scripts like this
NODE_ENV=dev npm run build
and in package.json, you would start a script/program
"scripts": {
"build":"node runner.js"
}
which would check the value of the environment variable to determine what to do. In runner.js I do something like the following
if (process.env.NODE_ENV){
switch(process.env.NODE_ENV){
....
}
}
For conditional npm scripts, you can use cross-platform basic logical operators to create if-like statements ( || and && ).
I've run into needing to run scripts to only generate helpers once on any machine. You can use inline javascript to do this by using process.exit() codes.
"scripts": {
"build":"(node -e \"if (! require('fs').existsSync('./bin/helpers')){process.exit(1)} \" || npm run setup-helpers) && npm run final-build-step"
}
So for testing envs you might do:
"scripts": {
"build":"node -e \"if (process.env.NODE_ENV === 'production'){process.exit(1)} \" || make install"
}
Can't you add another section in your .json under devDependencies? Then if you do npm install it'd install the packages specified under devDependincies and npm install --production would install the regular dependcies.
I would encourage you to take a different tack on uglifying your code. Take a look at connect-browserify or the even more powerful asset-rack.
These can automatically uglify your code on launch of the Express server, rather than on install. And you can configure them to do different things in development and production.

I canĀ“t install nodemon globally, "nodemon" not recognized

I want to use nodemon for monitoring my node.js app's, then I execute the next line command:
npm install -g nodemon
or
npm install nodemon -g
When I move to my app folder and try to to
nodemon app.js
The system tells to the next:
"nodemon 'is not recognized as an internal or external command, program or batch file.
Since node prefix is not in the PATH ENV variable , any of the globally installed modules are not getting recognized.
Please try this.
Open cmd prompt
npm config get prefix
append the resulting path to PATH env variable.
Now you should be able to run nodemon from any location.
This is what i have done on my local machine
C:\>npm config get prefix
C:\Users\username\AppData\Roaming\npm
C:\>set PATH=%PATH%;C:\Users\username\AppData\Roaming\npm;
C:\>nodemon
31 Jul 22:30:29 - [nodemon] v0.7.8
31 Jul 22:30:29 - [nodemon] to restart at any time, enter `rs`
31 Jul 22:30:29 - [nodemon] watching: C:\
31 Jul 22:30:29 - [nodemon] starting `node `
^CTerminate batch job (Y/N)? Y
I also got same error as you with this command:
$ sudo npm install -g nodemon
I just really switched as "root" and then just ran:
$ npm install -g nodemon
I think npm has a bug to not work with sudo, but it works fine when you are really "root".
Single line solution
In terminal
npm install -g --force nodemon
There is a problem with integrated terminal of vs code. when I try in external terminal nodemon works. But in integrated terminal, it gives bash: nodemon: command not found error.
so here is my solution
install nodemon as development dependency
npm install --save-dev nodemon
and change package.json of the project
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"nodemon": "./node_modules/.bin/nodemon"
},
to run nodemon type into terminal in project folder
npm run nodemon
Mine was I went to Control Panel and Repair the NodeJS app and tried to install again with npm install -g nodemon and now it works. Maybe you mixed up or something with Node.
check out here :-
npm install -g nodemon
and then run
$nodemon server.js
You won't need to install nodemon anymore, since Nodejs has finally introduced its --watch feature which restarts the process when an imported file is changed.
node --watch index.js
https://nodejs.org/en/blog/release/v18.11.0/
Linux users: I would highly suggest not using sudo or root user to install npm packages. This could become a security problem especially on a production system. I would also suggest not trying to hack permissions as I have hosed an Ubuntu system by not reading the warning on the npmjs procedure.
It would be better to configure npm to use a folder owned by the current user. Simplest approach
wget https://raw.githubusercontent.com/pcnate/npm-configure/master/add-npm-global.sh -q -O - | bash
npm install -g nodemon
Or get the code script on github to see how it works
See details on the npmjs website
On Windows, I was having issues installing nodemon directly from the Command line. Downloaded Cygwin and I was able to npm install nodemon instantly.
You can add path to node packages in System Path variable.
Add "C:\Users\UserName\AppData\Roaming\npm".
Even after adding path to System Path variable it did not work for me using nodemon. Then i used npm run serve to run the server. now it is up and running. Btw i am a windows user
This command worked for me.
If your global installation didn't work then install it in your
development dependency.
npm install --save-dev nodemon
Updated
After Path settings we also need to type in the following commands
Set-ExecutionPolicy Unrestricted
what this command enables running scripts on the system
I think some of us can't reach global environments without admin privileges.
If you tried everything and it's still not working, try running VSCode as administrator. It worked out for me.
had the same problem otherwise was just working fine a day ago.
Very simple fix
first check if nodemon exists on your system globally or not
To check
npm list -g --depth=0
If you don't see then install
it npm install -g nodemon (g stands for globally)
If you see it still doesn't work then you need to configure environment variable
I use Windows OS. On Windows navigate to
Control panel>System>Advanced System Settings>Environment Variables>double-click on PATH
Now check if you have this PATH C:\Users\yourUsername\AppData\Roaming\npm
If not, you will see some existing paths, just append to it separating with semicolon. That's it! Worked for me.
For me node was installed in C:..\Roaming\npm and for you if the PATH is different, you will put in whatever applcable.

Resources