Error: listen EADDRINUSE after restart - node.js

I have a Node app that I run on port 3000 locally. This error started popping up recently:
➜ web-frontend git:(feature/WEB-6880__CheckoutBackButton) yarn start
yarn run v1.2.1
events.js:160
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE :::3000
at Object.exports._errnoException (util.js:1022:11)
at exports._exceptionWithHostPort (util.js:1045:20)
at Server._listen2 (net.js:1259:14)
at listen (net.js:1295:10)
at Server.listen (net.js:1391:5)
at EventEmitter.listen (/Users/durham/Sites/web-frontend/node_modules/express/lib/application.js:618:24)
at Object.<anonymous> (/Users/durham/Sites/web-frontend/server/index.js:79:5)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
➜ web-frontend git:(feature/WEB-6880__CheckoutBackButton)
I would kill any process using that port and it would restart:
➜ ~ sudo lsof -i tcp:3000
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
httpd 1926 root 6u IPv6 0x99102dc7c7853bbb 0t0 TCP *:hbci (LISTEN)
httpd 1931 _www 6u IPv6 0x99102dc7c7853bbb 0t0 TCP *:hbci (LISTEN)
➜ ~ sudo kill -9 1926
➜ ~ sudo kill -9 1931
kill: 1931: No such process
➜ ~ z front
➜ web-frontend git:(feature/WEB-6880__CheckoutBackButton) yarn start
yarn run v1.2.1
$ export $(cat internals/env/dev); NODE_ENV=development node server
events.js:160
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE :::3000
at Object.exports._errnoException (util.js:1022:11)
at exports._exceptionWithHostPort (util.js:1045:20)
at Server._listen2 (net.js:1259:14)
at listen (net.js:1295:10)
at Server.listen (net.js:1391:5)
at EventEmitter.listen (/Users/hco/Sites/web-frontend/node_modules/express/lib/application.js:618:24)
at Object.<anonymous> (/Users/hco/Sites/web-frontend/server/index.js:79:5)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
error Command failed with exit code 1.
I restart my machine and try to start my app to the same error.
What might be the issue here? This is new and I can’t think of anything I’ve changed that might have caused it.
Express app code, as requested:
const express = require('express');
const logger = require('./logger');
const { sources } = require('../internals/config');
const argv = require('minimist')(process.argv.slice(2));
const setup = require('./middlewares/frontendMiddleware');
const path = require('path');
const resolve = require('path').resolve;
const fs = require('fs');
const morgan = require('morgan');
const app = express();
const DEFAULT_PORT = 3000;
/**
* Set up Morgan for logging errors to the server.
* All errors are logged to the `access.log` file in the directory the
* site is run from.
*/
const errorLog = process.env.NODE_ENV === 'production'
? '/var/log/web2/web2.log'
: path.join(process.cwd(), '../access.log');
// create a write stream (in append mode)
const accessLogStream = fs.createWriteStream(errorLog, { flags: 'a' });
// setup the logger
app.use(morgan('combined', {
skip: (req, res) => res.statusCode < 400, // eslint-disable-line no-magic-numbers
stream: accessLogStream
}));
// remove trailing slashes
app.use((req, res, next) => {
if (req.path.length > 1 && /\/$/.test(req.path)) {
const query = req.url.slice(req.path.length);
res.redirect(301, req.path.slice(0, -1) + query);
} else {
next();
}
});
// Proxy package so we can manage API requests with Node instead of the client.
const proxy = require('express-http-proxy');
/**
* Incorporate API middleware with proxy
* The proxy helps work around the CORS issue with standard Ajax requests
* on the client. There are further methods that can be taken advantage of with
* the express-http-proxy library. Take a look here:
* https://github.com/villadora/express-http-proxy
*
*
* Proxies requests for the H&Co API.
* Example URL to test: /api/v1/product_lines?sort=name
* API documentation: https://swagger.typography.com/api2/
*/
app.use('/api', proxy(sources.apiUrl, {
proxyReqOptDecorator: (proxyReq) => {
if (proxyReq.headers['authorization-api']) {
proxyReq.headers['Authorization'] = proxyReq.headers['authorization-api']; // eslint-disable-line
}
return proxyReq;
}
}));
// In production we need to pass these values in instead of relying on webpack
setup(app, {
outputPath: resolve(process.cwd(), 'build'),
publicPath: '/'
});
// get the intended port number, use port 3000 if not provided
const port = argv.port || process.env.PORT || DEFAULT_PORT;
// Start your app.
/* eslint consistent-return: 0 */
app.listen(port, (err) => {
if (err) {
return logger.error(err.message);
}
logger.appStarted(port, null, sources.apiUrl);
});

instead of using "app.listen", start your server like so:
const server = require("http").createServer(app);
server.listen(port, () => console.log("server started"));
then you'll be able to close the server and free the port when your app exits
function exit(message) {
if (message) console.log(message);
server.close();
process.exit();
}
process.on("exit", exit);
process.on("SIGINT", exit);
process.on("uncaughtException", exit);

Related

nodemon app crashed - waiting for file changes before starting ... Error

appjs
const express = require("express");
const path = require("path");
const homeRouter = require("./routes/home.routes");
const app = express();
const port = 8000;
app.use(express.static(path.join(__dirname, "assets")));
app.use(express.static(path.join(__dirname, "images")));
app.set("view engine", "ejs");
app.set("views", "views");
app.use("/", homeRouter);
app.listen(port, () => {
console.log(`server listen on port ${port}`);
});
home routes
const router = require('express').Router()
const homeController = require('../controllers/home.controller')
router.get('/', homeController.getHome)
module.exports = router
homecontroller
const productsModel = require('../models/products.models')
exports.getHome = (req,res,next) => {
//get products
//get render index.ejs
productsModel.getAllproducts().then(products => {
res.render('index', {
products: products
})
})
}
products.models
const mongoose = require("mongoose");
const DB_URL = 'mongodb://localhost:27017/shop'
const productsSchema = mongoose.Schema({
name:String,
image:String,
price:String,
category:String,
description:String
})
const product = mongoose.model('product', productsSchema)
exports.getAllproducts = () => {
//connect to db
//get products
//disconnect
return new Promise((resolve,reject) => {
mongoose.connect(DB_URL).then(() => {
return product.find({})
}).then(products => {
mongoose.disconnect()
resolve(products)
}).catch(err => reject(err))
})
}
Error
node:events:504
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE: address already in use :::8000
at Server.setupListenHandle [as _listen2] (node:net:1330:16)
at listenInCluster (node:net:1378:12)
at Server.listen (node:net:1465:7)
at Function.listen (C:\Users\islam\OneDrive\Desktop\shopnode\node_modules\express\lib\application.js:635:24)
at Object. (C:\Users\islam\OneDrive\Desktop\shopnode\app.js:17:5)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12) Emitted 'error' event on Server
instance at:
at emitErrorNT (node:net:1357:8)
at processTicksAndRejections (node:internal/process/task_queues:83:21) { code: 'EADDRINUSE',
errno: -4091, syscall: 'listen', address: '::', port: 8000 }
[nodemon] app crashed - waiting for file changes before starting...
In case we have some project running are both same port and on your server then catch this error and i have solve in that time.
open terminal set your Dir location and run this command on your terminal
doing this things
using this command :- pkill node
or
for mac :- sudo killall -9 node
or
for windows :- > killall -9 node
or
killall node
otherwise use this on your defined port modify your code
var port = process.env.PORT || 8000;
do all this things then server restart
npm start or node app.js

Got an error listen EADDRINUSE: address already in use :::5000 while restarting a server

So, I have a simple express server which connects to the mongoDB atlas by mongoose.
And for example I starting the server, everything works fine but when I do restart(no matter with nodemon or just by using node) I got an error:
Error: listen EADDRINUSE: address already in use :::5000
at Server.setupListenHandle [as _listen2] (net.js:1313:16)
at listenInCluster (net.js:1361:12)
at Server.listen (net.js:1447:7)
at Function.listen (C:\Users\Олег\e-commerce-mern\MERN-shop-app\node_modules\express\lib\application.js:618:24)
at Object.<anonymous> (C:\Users\Олег\e-commerce-mern\MERN-shop-app\backend\server.js:36:20)
at Module._compile (internal/modules/cjs/loader.js:1138:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
at Module.load (internal/modules/cjs/loader.js:986:32)
at Function.Module._load (internal/modules/cjs/loader.js:879:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
Emitted 'error' event on Server instance at:
at emitErrorNT (net.js:1340:8)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
code: 'EADDRINUSE',
errno: 'EADDRINUSE',
syscall: 'listen',
address: '::',
port: 5000
}
and after restarting one or few times my server starts working just fine without the error, but then, after saving again the problem repeats and i don't know why.
db.js:
const mongoose = require('mongoose');
const mongoConnection = () => {
return mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
});
};
module.exports = mongoConnection;
server.js:
const express = require('express');
const products = require('./data/products'); //my mock data
const dotenv = require('dotenv');
// eslint-disable-next-line no-unused-vars
const colors = require('colors');
const dbConnect = require('./config/db');
dotenv.config();
dbConnect()
.then(() => {
// callback();
console.log('db connected');
})
.catch((err) => {
console.error(`Error: ${error.message}`.red.underline.bold);
process.exit(1);
});
const app = express();
app.get('/', (req, res) => {
res.send('app is running');
});
app.get('/api/products', (req, res) => {
res.json(products);
});
app.get('/api/products/:id', (req, res) => {
const product = products.find((p) => p._id === req.params.id);
res.json(product);
});
const PORT = process.env.port || 5000;
const server = app.listen(PORT,
// eslint-disable-next-line max-len
console.log(`server running in ${process.env.NODE_ENV} on port ${PORT}`.yellow.bold));
process.on('unhandledRejection', (err) => {
console.log('err', err.name, err.message);
console.log('unhadled rejection');
server.close(() => {
process.exit(1);
});
});
As you see, nothing too fancy here, yes, I understand that my port isn't killed on restart but I don't understand that behaviour and how to prevent it.
P.S. I'm using windows.
This error raised because any application running on port 5000.
To fix it you just need to kill the running application on port 5000.
Follow the steps below:
Step 0: stop your application If you are currently trying to run it on port 5000
Step 1: run command prompt as administrator
Step 2: run
-->" netstat -ano | findstr :5000 " <--
command to find the running application's pid number.
Note: In my case it is 4208
Step 4: run taskkill /PID {pid number} /F to kill the running process.
Now you can run your app on port 5000
Update : Got a shortcut to kill the process
Just run TASKKILL /IM node.exe /F
Then start your application :-)

Error: listen EADDRINUSE: address already in use :::6000

i have started my server many times like 4000 5000 6000 but getting same answer, on my port throw er; // Unhandled 'error' event i dont know why i have changed it many times , i also kill my server with ctrl c and then re started but get same error Error: listen EADDRINUSE: address already in use :::6000
const express = require('express');
const app = express();
const Joi = require('joi');
app.use(express.json());
const port = 6000;
const courses =[
{ id:1,
name:'courses 1'},
{ id:2, name:'courses 2'},
{ id:1, name:'courses 3'},
];
app.get('/',(req,res)=>{
res.send("hellow request for this site has been successfully done");
});
app.get('/api/courses',(req,res)=>{
res.send(courses);
});
app.get('/api/courses/:id',(req,res)=>{
let course = courses.find(c=> c.id === parseInt (req.params.id));
if (!course)res.status(404).send('<h1> 404 found</h1>')
res.send(course);
});
app.put('/api/courses/:id',(req,res)=>{
let course = courses.find(c=> c.id === parseInt (req.params.id));
if (!course)res.status(404).send('<h1> 404 found</h1>')
const {error} = validateCourse(req.body);
if(error){
res.status(400).send(error)
return;
}
course.name = req.body.name;
res.send(course);
});
app.post('/api/courses',(req,res)=>{
const {error} = validateCourse(req.body);
if(error){
res.status(400).send(error)
return;
}
const course ={
id: courses.length + 1,
name : req.body.name
};
courses.push(course);
res.send(course);
});
app.listen(port,()=>{
console.log(" kokab your server is runing " + port)
})
// validatecourse for repetation of course
validateCourse = (course) =>{
const schema = {
name: Joi.string().min(3).required()
};
return result = Joi.validate(course, schema);
}
// terminal error
C:\Users\DELL\Desktop\node> node app
events.js:174
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE: address already in use :::6000
at Server.setupListenHandle [as _listen2] (net.js:1279:14)
at listenInCluster (net.js:1327:12)
at Server.listen (net.js:1414:7)
at Function.listen (C:\Users\DELL\Desktop\node\node_modules\express\lib\application.js:618:24)
at Object.<anonymous> (C:\Users\DELL\Desktop\node\app.js:53:5)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
Emitted 'error' event at:
at emitErrorNT (net.js:1306:8)
at process._tickCallback (internal/process/next_tick.js:63:19)
at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
Use Below command to kill the process
lsof -i:<port_number>
kill -9 <PID>
You can do it using the following ways
sudo kill $(lsof -t -i:PORT)
OR
sudo fuser -k -n tcp PORT
OR
fuser -k PORT/tcp
Please replace the PORT with the needed port.

How to host nodejS+postgres application on digital-ocean?

I have followed traversy media tutorial to deploy nodejs app on digital-ocean. I am using postgres database of digital ocean. However on running node app.js command I am getting error
I have tried to follow many answers on stackoverflow but they have not solved the problem
app.js
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const morgan = require('morgan')
const db = require('./queries') // contains all query functions
const port = 3000
const app = express()
app.use(morgan('combined'))
app.use(bodyParser.json())
app.use(
bodyParser.urlencoded({
extended: true,
})
)
app.use(cors())
app.get('/runs', db.getPlayers)
app.post('/year', db.getByYear)
//Handle production
app.use(express.static(__dirname+'/public/'))
//Handle SPA
app.get(/.*/, (request, response) => response.sendFile(__dirname+'/public/index.html') );
app.listen(port, () => {
console.log(`App running on port ${port}.`)
})
Error which I am getting is:-
events.js:183
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE :::3000
at Object._errnoException (util.js:1022:11)
at _exceptionWithHostPort (util.js:1044:20)
at Server.setupListenHandle [as _listen2] (net.js:1367:14)
at listenInCluster (net.js:1408:12)
at Server.listen (net.js:1492:7)
at Function.listen (/home/vineet/IPL-Stats-Analysis-Dashboard/node_modules/express/lib/application.js:618:24)
at Object.<anonymous> (/home/vineet/IPL-Stats-Analysis-Dashboard/app.js:63:5)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
I am not familiar with said tutorial - but the error denotes that another process (probably the same express app) is already listening on port 3000.
On Linux you can list all running process with the command ps aux. Look for another node process. If there is none - you can find which processes are listening on which ports by running lsof -Pnl +M -i4 for ipv4 addresses and lsof -Pnl +M -i6 for ipv6.
Or simply do curl http://localhost:3000 in the Digitalocean droplet.
If were your OS is Linux, just type on your terminal which is killall -9 node

Gulp-connect shows an error 'listen EADDRINUSE' 8080

I have a simple gulpfile.js:I have a simple gulpfile.js:I have a simple gulpfile.js:I have a simple gulpfile.js:I have a simple gulpfile.js:I have a simple gulpfile.js:I have a simple gulpfile.js:I have a simple gulpfile.js
var gulp = require('gulp');
var less = require('gulp-less');
var nodemon = require('gulp-nodemon');
var watch = require('gulp-watch-less');
var path = require('path');
var bower = require('gulp-bower');
var livereload = require('gulp-livereload');
var connect = require('gulp-connect');
gulp.task('connect', function() {
connect.server({
root: ['./'],
port:8080,
livereload: true
});
});
gulp.task('less', function() {
// Code for the default task
return gulp.src('less/style.less')
.pipe(less())
.pipe(gulp.dest('stylesheets'))
});
gulp.task('watch',function(){
gulp.watch('less/**/*.less',['less']);
});
gulp.task('start', function () {
nodemon({
script: 'server.js'
, ext: 'js html'
, env: { 'NODE_ENV': 'development' }
})
})
gulp.task('default', ['start', 'watch','less','connect']);
server.js
var http=require('http');
var express=require('express');
var jade=require('jade');
var app=express();
var chalk = require('chalk');
//var less = require('less');
//gestion des routes
var server=http.createServer(app);
var port = process.env.PORT || 8080;
app.set('view engine','jade');
app.use("/stylesheets",express.static(__dirname + "/stylesheets"));
app.use("/lib",express.static(__dirname + "/lib"));
app.use("/script",express.static(__dirname + "/script"));
app.use("/less",express.static(__dirname + "/less"));
app.use("/bower_components",express.static(__dirname + "/bower_components"));
app.use("/img",express.static(__dirname+"/img"));
app.use("/font",express.static(__dirname+"/font"));
app.use("/lib",express.static(__dirname+"/lib"));
app.get('/',function(req,res){
res.render('index');
});
when i run my application i get this error Any idea please ?:
**events.js:141
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE :::8080
at Object.exports._errnoException (util.js:870:11)
at exports._exceptionWithHostPort (util.js:893:20)
at Server._listen2 (net.js:1236:14)
at listen (net.js:1272:10)
at Server.listen (net.js:1368:5)
at Object.<anonymous> (C:\Users\achraf\Desktop\portfolio\server.js:52:8)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)**
console
λ gulp
[22:35:56] Using gulpfile ~\Desktop\portfolio\Gulpfile.js
[22:35:56] Starting 'start'...
[22:35:56] Finished 'start' after 5.68 ms
[22:35:56] Starting 'watch'...
[22:35:56] Finished 'watch' after 35 ms
[22:35:56] Starting 'less'...
[22:35:56] Starting 'connect'...
[22:35:56] Finished 'connect' after 23 ms
[22:35:57] Server started https://localhost:8080
[22:35:57] LiveReload started on port 35729
[22:35:57] [nodemon] 1.8.1
[22:35:57] [nodemon] to restart at any time, enter `rs`
[22:35:57] [nodemon] watching: *.*
[22:35:57] [nodemon] starting `node server.js`
[22:35:57] Finished 'less' after 402 ms
[22:35:57] Starting 'default'...
[22:35:57] Finished 'default' after 25 μs
events.js:141
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE :::8080
at Object.exports._errnoException (util.js:870:11)
at exports._exceptionWithHostPort (util.js:893:20)
at Server._listen2 (net.js:1236:14)
at listen (net.js:1272:10)
at Server.listen (net.js:1368:5)
at Object.<anonymous> (C:\Users\achraf\Desktop\portfolio\server.js:52:8)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
[22:35:59] [nodemon] app crashed - waiting for file changes before starting...
Seems like the specified port (8080) is already in use by another process.
Run the following command to check the running process:
netstat -tulpn | grep :8080
Or try a different port in your server.js
var port = process.env.PORT || 4000;
I've got same issue with gulp-connect. You just need to change port in your gulpfile.js to another.
gulp.task('connect', function() {
connect.server({
root: 'app',
port: 8090,
livereload: true
});
});

Resources