This question already has answers here:
Node.js app can't run on port 80 even though there's no other process blocking the port
(8 answers)
Closed 6 years ago.
I'm trying to setup Socket.io with Express, and I'm using the exact code from the Socket.io documentation, which is this:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
The error I'm getting when I'm running app.js is this:
events.js:141
throw er; // Unhandled 'error' event
^
Error: listen EACCES 0.0.0.0:80
at Object.exports._errnoException (util.js:849:11)
at exports._exceptionWithHostPort (util.js:872:20)
at Server._listen2 (net.js:1218:19)
at listen (net.js:1267:10)
at Server.listen (net.js:1363:5)
at Object.<anonymous> (/Users/leondewit/PhpstormProjects/websocket_test/app.js:5:8)
at Module._compile (module.js:434:26)
at Object.Module._extensions..js (module.js:452:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
Does anyone know what might be wrong?
You cannot bind to ports lower than 1024 in a system without sudo or admin permissions.
These ports are called privileged ports, here is a link to a wikipedia article with some ports and their associated services
Ideally when you are developing, for ease of use, you should uses a number generally higher than 3000 to be safe.
Related
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
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);
I have this code in a file named server.js:
var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
io.on('connection', function(){
console.log("a client connected");
});
server.listen(80);
When i run node server.js in the terminal (cmd), it throws this error:
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EACCES
at errnoException (net.js:904:11)
at Server._listen2 (net.js:1023:19)
at listen (net.js:1064:10)
at Server.listen (net.js:1138:5)
at Object.<anonymous> (C:\inetpub\wwwroot\socketio\server.js:9: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)
Do you have an idea of what could be the problem? Thanks!
Note: I already have socket.io and express installed.
It seems you are not allowed to open a serversocket on port 80.
See this line in the error message
C:\inetpub\wwwroot\socketio\server.js:9:8
Socket addresses smaller than 1024 are reserved for system use. Try this:
var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
io.on('connection', function(){
console.log("a client connected");
});
server.listen(3000);
Looks like the port 80, is invalid or unacceptable. I tried to change it to another port (8000) and it worked.
server.listen(8000);
The exception is gone. I hope I can find a way to distinguish between valid/invalid ports at run-time.
I use fs library for reading file from system. I don't know I use this library and meet error.
I'm using PhpStorm. at line : fs.readFile() : there's a line under that, that notice me : unresolved function or method readFile(). It means IDE doesn't figure out where is this function. Nevertheless, I have checked fs.js and I see no problem.
I receive this error when running:
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:1127:5)
at Object. (/home/hqt/PhpstormProjects/NodeApp/sample/AsynchronouslyReading.js:21:4)
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)
Here is my code :
var http = require('http');
var fs = require('fs');
// create http server
http.createServer(function(req, res) {
fs.readFile('helloworld.js', 'utf-8', function(err, data) {
res.writeHead(200, {'content-type' : 'text/plain'});
if (err) res.write('could not find or open file');
else res.write(data);
// ending
res.end();
});
}).listen(8124, function() {console.log('server is running at 8124');});
console.log('server is runnint at 8124 port');
Please help me figure out why. I'm using Ubuntu machine for development.
Thanks :)
That's because something else is already listening on port 8124. On Linux, you can use something like netstat -tanp | grep LISTEN | grep 8124 to see what.
I am trying to take the first command line argument as the port to run node on.
The following code is not working in node.js:
try {
if(process.argv[2] == undefined) {
throw new Error("no port specified");
}
var port = process.argv[0];
console.log(port);
}
catch (err) {
console.log("Error give port number as the argument");
return;
}
require('http').createServer(function handleRequest(req, res) {
res.writeHead(200, {'content-type' : 'text/plain'});
res.end('Hello World!');
}).listen(port);
It gives the following error:
$ node server.js 8080
node
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at errnoException (net.js:884:11)
at Server._listen2 (net.js:1003:19)
at listen (net.js:1044:10)
at Server.listen (net.js:1104:5)
at Object.<anonymous> (/home/studiet/Documents/Aptana Studio 3 Workspace/nodef2b/server.js:19:4)
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)
I know that node.js is asyncronous, but in this case I thought nothing was waiting for anything. What is wrong? How can I make the system wait for whatever is taking too long here, and what is taking too long? Or, what else is wrong?
EDIT: line 19 in the code is where I .listen(port);
EADDRINUSE stands for Error Address In Use.
Some other process is using port 80.
You need to find that process and terminate it with extreme prejudice.
EDIT: In this case, it means an invalid port number.
As you can see from your first line of output, port is "node", not 8080.
You need to set it to argv[2].