Changing Node.js listening port


I just installed node.js on Windows. I have this simple code which does not run:

I get: Error: listen EADDRINUSE

Is there a config file that tells node.js to listen on a specific port?

The problem is I have Apache listening on port 80 already.


var http = require('http'); 
var url = require('url'); 

http.createServer(function (req, res) { 
 console.log("Request: " + req.method + " to " + req.url); 
 res.writeHead(200, "OK"); 
 res.write("<h1>Hello</h1>Node.js is working"); 
console.log("Ready on port 5454");
8/29/2012 3:25:17 PM

Accepted Answer

There is no config file unless you create one yourself. However, the port is a parameter of the listen() function. For example, to listen on port 8124:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8124, "");
console.log('Server running at');

If you're having problems finding a port that's open, you can go to the command line and type:

netstat -ano

To see a list of all ports in use per adapter.

5/23/2017 12:10:26 PM

I usually manually set the port that I am listening on in the app.js file (assuming you are using express.js

var server = app.listen(8080, function() {
    console.log('Ready on port %d', server.address().port);

This will log Ready on port 8080 to your console.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow