Thursday, March 29, 2012

Include other files and call function from other class

Require another file 



Create a file called index.js and paste the following code

      var server = require("./server");
      server.start(router.route, handle);

Now create a new file name it server.js and paste the following code

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

      function start(route, handle) {
       function onRequest(request, response) {
        var pathname = url.parse(request.url).pathname;
        console.log("Request for  received.");
         }  
        http.createServer(onRequest).listen(8888);
       console.log("Server has started.");
       }
   exports.start = start;

Now run index.js

node index.js

The result wll be

"Server has started"

Now open your browser and type http://localhost:8888/

Now the server will respond with "Request for  received."

No comments: