I have created a nodejs http server
var http = require("http");
var url = require("url");
var express = require('express');
var app = express();
function start(route, handle){
function onRequest(request,response){
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
route(handle, pathname, response, request);
}
http.createServer(onRequest).listen(8888);
console.log("Server has started");
app.listen(8888);
console.log('Express app listening on port 8888');
}
it gives error
f:\Labs\nodejs\webapp>node index.js
Server has started
Express app listening on port 8888
events.js:66
throw arguments[1]; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at errnoException (net.js:769:11)
at Server._listen2 (net.js:909:14)
at listen (net.js:936:10)
at Server.listen (net.js:985:5)
at Function.app.listen (f:\Labs\nodejs\webapp\node_modules\express\lib\appli
cation.js:532:24)
at Object.start (f:\Labs\nodejs\webapp\server.js:15:6)
at Object.<anonymous> (f:\Labs\nodejs\webapp\index.js:11:8)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
when i change the port of app.listen it dont throw this error, what can be done?
will changing port other than server port will keep the session of the server on another port??
and how can i access this app variable in other js page to get/set the data?
You can't have multiple things listening on the same port like this, hence the EADDRINUSE
error. If you want to create your own http server while using Express, you can do it like this:
var express = require('express');
var https = require('https');
var http = require('http');
var app = express();
http.createServer(app).listen(8888);
https.createServer(options, app).listen(443);
From the Express docs:
The app returned by express() is in fact a JavaScript Function, designed to be passed to node's http servers as a callback to handle requests.
Or you can just do
app.listen(8888);
And then Express will setup an http
server for you.
You would then set up your routes in Express to actually handle requests coming in. With Express, routes look like this:
app.get('/foo/:fooId', function(req, res, next) {
// get foo and then render a template
res.render('foo.html', foo);
});
If you want to access your app
in other modules (usually for testing) you can just export it like any other variable:
module.exports.app = app;
You'll then be able to require('./app').app
in other modules.
If you intend to run on the same port, you can see if you have currently running node processes with
ps aux | grep node
and then kill -9 PROCESSID