0

everytime i am doing some change to code and then run it this error comes i have changed many ports and dont know the reason behind it . Also please explains process.env.PORT meaning and its significance , thanks in advance

index.js

/*******installed modules****** */
        const express = require('express')
        const mongoose = require('mongoose')
        const path = require('path')
    
    /*****user created modules******* */
    const User = require('./model/user')
    const PORT = 8005
    
    
    const app = express()
    
    /*********middlewares**********/
    app.use(express.urlencoded({ extended: true }));
    app.use(express.json());
    app.use(express.static('static'))
    
    
    
    
    /******view engine*********** */
    app.set('views', path.join(__dirname, 'views'));
    
    // Set view engine as EJS
    app.engine('html', require('ejs').renderFile);
    app.set('view engine', 'html');
    
    
    
    
    /********connect with mongoDb cloud********/
    const mongoUrl = 'mongodb+srv://admin:{my_key}@cluster0.zskv7.mongodb.net/myFirstDatabase?retryWrites=true&w=majority'
    mongoose.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true });
    mongoose.connection.on("connected", () => {
        console.log("connected to mongoDb");
    });
    
    
    
    /*********get request to check if server is working properly*********/
    
    app.get('/', (req, res) => {
        res.render('index')
    })
    
    app.use('/favgame', (req, res) => {
        const { name, fav_game } = req.body
        User.find({ name: name })
            .then((oldUser) => {
                if (oldUser) {
                    return res
                        .status(422)
                        .json({ error: "user already exists in the database" });
                }
                //if user does not exists initially
                //create new user with these details
                const user = new User(req.body);
                user
                    .save()
                    .then((user) => {
                        res.json({ message: "successfully saved" })
                        console.log('User saved successfully')
                    })
                    .catch((err) => {
                        res.send("Error", err)
                        console.log('cannot create user some error');
                    });
            })
    })
    
    
    
    
    /**********listening on server************ */
    app.listen(PORT, (err) => {
        if (err) {
            return console.log(err);
        }
        console.log(`Server started on PORT: ${PORT}`);
    })

error coming

node:events:342
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE: address already in use :::8005
    at Server.setupListenHandle [as _listen2] (node:net:1306:16)
    at listenInCluster (node:net:1354:12)
    at Server.listen (node:net:1441:7)
    at Function.listen (/home/dhruv/Desktop/quiz_question/node_modules/express/lib/application.js:618:24)
    at Object.<anonymous> (/home/dhruv/Desktop/quiz_question/index.js:75:5)
    at Module._compile (node:internal/modules/cjs/loader:1109:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1138:10)
    at Module.load (node:internal/modules/cjs/loader:989:32)
    at Function.Module._load (node:internal/modules/cjs/loader:829:14)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
    at node:internal/main/run_main_module:17:47
Emitted 'error' event on Server instance at:
    at emitErrorNT (node:net:1333:8)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  code: 'EADDRINUSE',
  errno: -98,
  syscall: 'listen',
  address: '::',
  port: 8005
}

i have checked previous questions posted on the similar title but didnt get help from it and error is not resolved by appyling those changes , i know error is very basic but not able to figure it out

dhruv singhal
  • 73
  • 3
  • 9

1 Answers1

2

You are getting this error because the program itself is running (and using the specified port) and you are trying to run it again, simple solution is to stop the program first then run it again to apply changes, a better solution is to use a hot-reload helper package like nodemon you can install it with:

npm install -g nodemon

and use it like so to run

nodemon index.js

this will stop and rerun the server on code change save.

About process.env.PORT, process.env in general is the environment variables object, defined by OS or any other tool that populates environment variables, environment variables are in KEY:VALUE form PORT is simply the key of defined environment variable and process.env.PORT yields the value of the PORT environment variable.

  • ctrl + C does not kill the server? – dhruv singhal May 29 '21 at 06:02
  • It doesn't do it gracefully, so the port will stay as used for a while after killing the process. see https://hackernoon.com/graceful-shutdown-in-nodejs-2f8f59d1c357 and https://stackoverflow.com/questions/44788982/node-js-ctrl-c-doesnt-stop-server-after-starting-server-with-npm-start – Mahan Zendedel May 29 '21 at 06:18