简体   繁体   中英

Node.js how to set server environment PORT and NODE_ENV?

How do I set the server environment to a certain port?

For instance,

const app = require('express')()
const isProd = (process.env.NODE_ENV === 'production')
const port = process.env.PORT || 3000

I will always get false for isProd and 3000 for port

I don't see the usefulness of these two lines and I can just set them below manually:

app.get('/', function (req, res) {
  const data = {message: 'Hello World!'}
  return res.status(200).json(data);
})

app.listen(3000, function () {
  console.log('listening on port 3030!')
})

Do I need some config file in my root?

Any ideas?

I am using Linux/ Ubuntu/ Kubuntu.

Try running your server using below command

set NODE_ENV=production && set PORT=7000 && node server.js

Or for Linux

NODE_ENV=production PORT=7000 node server.js

This will set environment and port for your Node server.

Depends a bit on where you're hosting (eg windows or *nix) and how you're running your app (as a Windows or Linux service, using pm2, using systemd, etc).

The simplest way is to just change the command line call you start your app with, eg (linux):

NODE_ENV=prod PORT=34567 node myapp.js

or Windows

set NODE_ENV=prod && set PORT=34567 && node myapp.js

If you're using systemd or pm2 (and you should be), then they each have config files that allow you to set those variables for the environment the server is running in.

Pm2 docs: http://pm2.keymetrics.io/docs/usage/application-declaration/

Locally, you can just set defaults in your environment through normal means (in *nix that means exporting them in your shell config)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM