Following is my code -
apps.js
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/api/users', (_req, res) => {
res.send('Hello World');
})
app.listen(PORT, () => {
console.log(`Server running on port: `, PORT);
});
.env file
PORT=8000
Now when I run the program though terminal via command - node app.js
I am getting -
Server running on port: 3000
but I want it to run on 8000 and pick it from .env file. Let me know what I am doing wrong here.
I know while running from terminal I can define PORT=8000
or app.set()
but I am looking to pick it from an environment file. Let me know what I am doing wrong here / in terms of understanding.
CodePudding user response:
You can use dotenv
npm package for custom environment variables.
Usage
Create a .env
file in the root of your project:
PORT=8000
As early as possible in your application, import and configure dotenv:
require('dotenv').config();
// Your .env variables is now available in process.env object
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/api/users', (_req, res) => {
res.send('Hello World');
})
app.listen(PORT, () => {
console.log(`Server running on port: `, PORT);
});
Read more in the official package: dotenv