Saturday, June 3, 2017

Node.js 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)






No comments:

Post a Comment