Monday 28 January 2019

nodejs modules





What is Modules?
A module encapsulates related code into a single unit of code. When creating a module, this can be interpreted as moving all related functions into a file.


How to create Module
Create a module that returns the current date and time:



      exports.myDateTime = function () {
    return Date();
}; 
  
Save the code above in a file called "firstmodule.js"
Now we  can include and use the module in any of our Node.js files.
var http = require('http');
var dt = require('./myfirstmodule');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write("The date and time is currently: " + dt.myDateTime());
    res.end();
}).listen(8080);
  Save the code above in a file called "demo_module.js", and initiate the file

  Initiate demo_module.js in Terminal
      C:\Users\Your Name> node demo_module.js 
  If we want result,We will use this path http://localhost:8080

 Node.js HTTP Module
      This allows Node.js to transfer data over the Hyper Text Transfer Protocol (HTTP).

      var http = require('http');

//create a server object:
http.createServer(function (req, res) {
  res.write('Hello World!'); //write a response to the client
  res.end(); //end the response
}).listen(8080); //the server object listens on port 8080

     Save the code above in a file called "demo_http.js" 
     Then use below code in terminal
     C:\Users\Your Name>node demo_http.js
     Then use port to open browser
                out put:
                           
                       Hello World!

 Node.js URL Module

Create two html files and save them in the same folder as your node.js files.

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

http.createServer(function (req, res) {
  var q = url.parse(req.url, true);
  var filename = "." + q.pathname;
  fs.readFile(filename, function(err, data) {
    if (err) {
      res.writeHead(404, {'Content-Type': 'text/html'});
      return res.end("404 Not Found");
    }
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080); 

   node demo_fileserver.js 

   http://localhost:8080/(htmlfilename)

0 comments:

Post a Comment