gbade_ gbade_ - 2 months ago 7
Javascript Question

error starting HTTP server in node.js

I am trying to start a HTTP server from an index.js page. I have been reading The Node Beginner and following the tutorial there but each time i try starting a HTTP server, i get an error. This is the code

Server.js -

var http = require("http");
function start() {
function onRequest(request, response) {
console.log("Request received.");
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(10000);
console.log("Server has started.");
}


and then, index.js -

var server = require("./server");
server.start();


But each time i try running index.js, i get this error -

server.start();
^
TypeError: Object #<Object> has no method 'start'
at Object.<anonymous> (C:\wamp\www\nodeStack\index.js:2: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)
at startup (node.js:119:16)
at node.js:901:3
Program exited.


Please how do i resolve this, thanks.

Answer

You must change your server.js to export function start. You can also read very good explanation about module.exports here: What is the purpose of NodeJS module.exports and how do you use it?

var http = require("http");
var server = module.exports = {};

server.start = function () {
    function onRequest(request, response) {
       console.log("Request received.");
       response.writeHead(200, {"Content-Type": "text/plain"});
       response.write("Hello World");
       response.end();
    }
    http.createServer(onRequest).listen(10000);
    console.log("Server has started.");
};