This question already has answers here:
How to fix Error: listen EADDRINUSE while using NodeJS?
(45 answers)
Closed 6 years ago.
this is my firs program on NodeJs and i', trying to use Express and Socket.io on that. after create simple project as below code, i get
throw er; // Unhandled 'error' event
error, i'm google more tutorials but i cant find whats my code problem
install packages:
{
"name": "signalAndroidServerApplication",
"version": "0.0.0",
"private": true,
"dependencies": {
"body-parser": "~1.12.4",
"cookie-parser": "~1.3.5",
"express": "~4.12.4",
"socket.io": "latest"
}
}
my nodejs:
var socket = require('socket.io');
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = socket.listen(server);
var port = process.env.PORT || 3000;
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
io.on('connection', function (socket) {
socket.on('new_count_message', function (data) {
console.log('new_count_message' + data);
io.sockets.emit('new_count_message', {
new_count_message: data.new_count_message
});
});
});
full error:
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at errnoException (net.js:901:11)
at Server._listen2 (net.js:1039:14)
at listen (net.js:1061:10)
at Server.listen (net.js:1135:5)
at Object.<anonymous> (/var/www/signal/nodeJs/server.js:8:8)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
Error: listen EADDRINUSE means that the port you're trying to run on is already being used.
Try changing to it to use another port.
So var port = process.env.PORT || 3000; change this to var port = process.env.PORT || 4000; and hit localhost:4000
Related
I have a Node JS app which serves as a backend for a React web app. The application when started serves the React app and handles all the API calls. I connect to a MySQL database for data fetch. The app runs normally on local environment but crashes when deployed on an Ubuntu server(on AWS). On server, the app starts normally but after few seconds it crashes.
This is the error it throws when started
Error connecting: Error: connect ETIMEDOUT
at PoolConnection.Connection._handleConnectTimeout (/home/ubuntu/localSystem/node_modules/mysql/lib/Connection.js:412:13)
at Object.onceWrapper (events.js:313:30)
at emitNone (events.js:106:13)
at Socket.emit (events.js:208:7)
at Socket._onTimeout (net.js:422:8)
at ontimeout (timers.js:498:11)
at tryOnTimeout (timers.js:323:5)
at Timer.listOnTimeout (timers.js:290:5)
--------------------
at Protocol._enqueue (/home/ubuntu/localSystem/node_modules/mysql/lib/protocol/Protocol.js:144:48)
at Protocol.handshake (/home/ubuntu/localSystem/node_modules/mysql/lib/protocol/Protocol.js:51:23)
at PoolConnection.connect (/home/ubuntu/localSystem/node_modules/mysql/lib/Connection.js:119:18)
at Pool.getConnection (/home/ubuntu/localSystem/node_modules/mysql/lib/Pool.js:48:16)
at Object.<anonymous> (/home/ubuntu/localSystem/model/db.js:29:12)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
DB connection file (db.js):
var connection = mysql.createPool({
connectionLimit: 100,
host : 'xxxx',
port : xxxx,
user : 'username',
password : 'password',
database : 'myDB'
});
connection.getConnection(function(err) {
if (err) {
console.log('Error connecting: ' + err.stack)
return;
}
console.log('Connected as id ' + connection.threadId)
});
module.exports = connection;
Server.js
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
app = express();
var appRoutes = require('./routes/appRoutes');
app.use(express.static(path.join(__dirname, './client/build')));
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', appRoutes);
module.exports = app;
index.js
var app = require('./server');
//const { connection } = require('./database');
var port = 5001;
app.set('port', port);
app.listen(app.get('port'), () => {
console.log(`server on port ${app.get('port')}`);
});
AppModel.js
var sql = require('./db.js');
//Task object constructor
var Task = function(task){
this.task = task.task;
this.status = task.status;
this.created_at = new Date();
};
Task.getAllCustomerStatusRecords = function getAllCustomerStatusRecords(result) {
sql.query("Select a, b, c, call_provider_id from myTable order by id desc limit 20", function (err, res) {
if(err) {
console.log("error: ", err);
result(null, err);
}
else {
console.log('Customer status records : ', res);
result(null, res);
}
});
sql.releaseConnection()
};
I have a similar set up for another Node app but without mysql and it runs without issues.I'm not sure why it crashes in this case.
EDIT:
The API request does make a DB call. However that is only when the user explicitly selects some options and then makes a fetch call on the webpage. Initially though, there are no outwards API calls either to Db or external services.
I am getting an EADDRINUSE error on nodejs when trying to run this code:
const express = require('express')
const http = require('http')
const hostname = 'localhost'
const port = 3000
const app = express()
app.use((req, res, next) => {
console.log(req.headers)
res.statusCode = 200
res.setHeader('Content-Type', 'text/html')
res.end('<html><body><h1>This is response</h1></body></html>')
})
server.listen(hostname,port, () => {
console.log(`Server running at http:${hostname}//:${port}`)
})
const server = http.createServer(app)
server.listen(hostname,port, () => {
console.log(`Server running at http:{}//:${port}`)
})
I tried changing the ports but it still gave the same error.
The peculiar this is that if I remove the hostname - "localhost" and only listen to the port the code works.
Please explain what could be the issue?
Here is the stack trace :
events.js:183
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE localhost
at Object._errnoException (util.js:1022:11)
at _exceptionWithHostPort (util.js:1044:20)
at Server.setupListenHandle [as _listen2] (net.js:1350:19)
at listenInCluster (net.js:1408:12)
at Server.listen (net.js:1503:5)
at Object.<anonymous> (/media/shikhar/D/Study/git-test/node-express/index.js:30:8)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
So it's the first ever program I write but when I run it in the console I get this error.
module.js:540
throw err;
^
Error: Cannot find module 'C:\Users\Daniel\Desktop\app'
at Function.Module._resolveFilename (module.js:538:15)
at Function.Module._load (module.js:468:25)
at Function.Module.runMain (module.js:684:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
I have no idea why this is happening as I am new but I checked the code and nothing is wrong.
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-type', 'text/plain');
res.end('Hello World!');
});
server.listen(port, hostname, () => {
console.log('Server started on port '+port);
});
It seems like the script you wanted to execute isn't named "app".
Check the Path and name of your script when you execute it with the node command.
I am trying to implement Socket IO with my angular Js project. I am new into this, please help.
This is my server.js file
var express = require('express');
var path = require('path');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var port = 8080;
app.use(express.static(path.join(__dirname, "app")));
io.on('connection'), function(socket){
console.log('new connection made');
}
server.listen(port, function(){
console.log('Listening to port '+ port);
})
I have copied the socket.io.js file from socket.io-client and put it in my lib folder. So my index.html has
<script src="lib/js/socket.io.js"></script>
//all other includes required
<body>
//code here
</body>
heres is the error I get to see when I execute nodemon server.js
[nodemon] starting `node server.js`
events.js:216
throw new TypeError('"listener" argument must be a function');
^
TypeError: "listener" argument must be a function
at _addListener (events.js:216:11)
at Namespace.addListener (events.js:275:10)
at Server.(anonymous function) [as on]
(D:\SocketIOExperiment\ProjExperiment\node_modules\socket.io\lib\index
.js:456:29)
at Object.<anonymous>
(D:\SocketIOProject\SmartAdminExperiment\server.js:11:4)
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)
[nodemon] app crashed - waiting for file changes before starting...
Small typo on your code.Try this :
var express = require('express');
var path = require('path');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var port = 8080;
app.use(express.static(path.join(__dirname, "app")));
io.on(('connection'), function(socket){
console.log('new connection made');
})
server.listen(port, function(){
console.log('Listening to port '+ port);
})
Remember, io.on(event,cb) is a function call that registers the cb function to the event.
I was starting to learn NodeJS and when I implemented the first script, I get the following error:
http.listen(3000,() => console.log('Server running on port 3000'));
^
TypeError: http.listen is not a function
at Object.<anonymous> (C:\Users\I322764\Documents\Node\HelloNode.js:11:6)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:313:12)
at Function.Module.runMain (module.js:467:10)
at startup (node.js:136:18)
at node.js:963:3
The corresponding script is as follows:
'use strict';
const http = require('http');
http.createServer(
(req, res) => {
res.writeHead(200, {'Content-type':'text/html'});
res.end('<h1>Hello NodeJS</h1>');
}
);
http.listen(3000,() => console.log('Server running on port 3000'));
The version of node is 4.2.4
When you write:-
http.createServer(function(req,res){
res.writeHead(200);
res.end("Hello world");
});
http.listen(3000);
http.createServer() returns an object called Server. That Server object has listen method available. And you are trying to access that listen method from the http itself. That's why it shows that error.
so you can write it like:-
var server=http.createServer(function(req,res){
res.writeHead(200);
res.end("Hello world");
});
server.listen(3000,function(){
console.log('Server running on port 3000')
});
Now it will let your server listen on the port 3000.
listen isn't a function of http, but a method of the server you create with createServer:
var server = http.createServer((req, res) => {
res.writeHead(200, {'Content-type':'text/html'});
res.end('<h1>Hello NodeJS</h1>');
});
server.listen(3000,() => console.log('Server running on port 3000'));