setting node process.env when running express.js
setting node process.env when running express.js
i have following server.js file i want to specyfy PORT WHEN running express.js through cmd
something like
PORT=4000 node server.js
but when i do i get the error
'PORT=4000' is not recognized as the name of a cmdlet
i have also tried to use SET
SET PORT=4000
but it doesn't work
const express = require('express' );
const app = express();
app.use(express.static(__dirname));
const path=require('path');
var port=process.env.PORT || 53000
app.get('/',(req,res)=>
res.sendfile(path.join(__dirname)+'/index.html');
);
app.listen(port);
Where's the code where you try to set the PORT environment variable that generates an error? I don't see any code that attempts to do that.
– jfriend00
Aug 19 at 4:54
@jfriend00 , i set it when i want to run server.js via command line PORT=4000 node server.js
– Arash
Aug 19 at 5:04
Please show the exact command line you're attempting to run and describe what OS and command shell you're running it on. As it stands how, your question doesn't contain enough information for anyone to know what you're currently doing or what the environment is. The express code you show is pretty much irrelevant to the problem except to confirm that you're trying to read the environment variable. Setting the environment variable before running your node program is an OS and command shell issue, not a node.js code issue.
– jfriend00
Aug 19 at 5:11
In the Windows cmd shell, you would put
set PORT=4000
on one line and hit return to execute it and then put node server.js
on the next line and hit return to execute it. Or, you could create a batch file to do both lines for you.– jfriend00
Aug 19 at 5:12
set PORT=4000
node server.js
1 Answer
1
Different shells have different syntax for this. Try:
Windows cmd: cmd /C "set PORT=4000 && node script.js"
cmd /C "set PORT=4000 && node script.js"
Bash: PORT=4000 bash -c 'node script.js'
PORT=4000 bash -c 'node script.js'
Fish: env PORT=4000 node script.js
env PORT=4000 node script.js
Are you on Windows command prompt?
yes i am at windows command prompt .
– Arash
Aug 19 at 5:44
thanks , actually the issue was with powershell , i was running the set port=4000 from powershell .
– Arash
Aug 19 at 5:49
What's the correct syntax in powershell? Feel free to edit this answer and add that if it helps others.
– Charlie Schliesser
Aug 19 at 5:50
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
I assume because I see "process.env.PORT" that you could set that in your webpack (if using webpack)?
– Chris Cousins
Aug 19 at 4:25