NodeJS_Unit_2

Node JS Module

    • Module in Node.js is a simple or complex functionality organized in single or multiple JavaScript files which can be reused throughout the Node.js application.
    • Each module in Node.js has its own context, so it cannot interfere with other modules or pollute global scope.
    • Also, each module can be placed in a separate .js file under a separate folder.
    • Node.js implements CommonJS modules standard.
    • CommonJS is a group of volunteers who define JavaScript standards for web server, desktop, and console application.

Functions

    Functions are first class citizens in Node's JavaScript, similar to the browser's JavaScript. A function can have attributes and properties also. It can be treated like a class in JavaScript.

    Example: Function
      function Display(x) {
      console.log(x);
      }
      Display(100);

Buffer

    • Node.js includes an additional data type called Buffer (not available in browser's JavaScript). Buffer is mainly used to store binary data, while reading from a file or receiving packets over the network.
    • Buffer class is a global class. It can be accessed in application without importing buffer module.

    Node.js Creating Buffers

    There are many ways to construct a Node buffer. Following are the three mostly used methods:

    Create an uninitiated buffer:
    Following is the syntax of creating an uninitiated buffer of 10 octets:
    var buf = new Buffer(10);

    Create a buffer from array:
    Following is the syntax to create a Buffer given array:
    var buf = new Buffer([10, 20, 30, 40, 50]);

    Create a buffer from string:
    Following is the syntax to create a Buffer from a given string and optionally encoding type:
    var buf = new Buffer("Simply Easy Learning", "utf-8");

    Writing to Buffers in Node.js:

    The buf.write() method is used to write data into a node buffer.
    Syntax:
    buf.write( string, offset, length, encoding );

    The buf.write() method is used to return the number of octets in which string is written. If buffer does not have enough space to fit the entire string, it will write a part of the string.

    The buf.write() method accepts the following parameters:
    • String: It specifies the string data which is to be written into the buffer.
    • offset: It specifies the index at which buffer starts writing. Its default value is 0.
    • length: It specifies the number of bytes to write. Its default value is buffer.length.
    • encoding: It specifies the encoding mechanism. Its default value is ‘utf-8’.
    Example: Create a buffer.js file containing the following codes.

      //app.js
      cbuf = new Buffer(256);
      b_len = cbuf.write("Learn Programming with NodeJS!!");
      console.log("No. of Octets in which string is written: "+ b_len);

Module Types

    Node.js includes three types of modules:
    • Core Modules
    • Local Modules
    • Third Party Modules

Core Modules

    • The core modules include bare (basic) minimum functionalities of Node.js.
    • These core modules are compiled into its binary distribution and load automatically when Node.js process starts.
    • However, you need to import the core module first in order to use it in your application.

    Core Module Description
    http http module includes classes, methods and events to create Node.js http server.
    url url module includes methods for URL resolution and parsing.
    querystring querystring module includes methods to deal with query string.
    path path module includes methods to deal with file paths.
    fs fs module includes classes, methods, and events to work with file I/O.
    util util module includes utility functions useful for programmers.

Loading Core Modules

    • In order to use Node.js core or NPM modules, you first need to import it using require() function as shown below.
    var module = require('module_name');
    • As per above syntax, specify the module name in the require() function. The require() function will return an object, function, property or any other JavaScript type, depending on what the specified module returns.
    • The following example demonstrates how to use Node.js http module to create a web server.

    Example: Load and Use Core http Module
      var http = require('http');
      var server = http.createServer(function(req, res)
      {
      //write code here
      });
      server.Listen(5000);


    In the above example, require() function returns an object because http module returns its functionality as an object, you can then use its properties and methods using dot notation e.g. http.createServer().

Local Modules

    • Node.js comes with different predefined modules (e.g. http, fs, path, etc.) that we use and scale our project.
    • Local modules are modules created locally in your Node.js application.
    • These modules include different functionalities of your application in separate files and folders.
    • For example, if you need to connect to MongoDB and fetch data then you can create a module for it, which can be reused in your application.

Defining local module:

Local module must be written in a separate JavaScript file. In the separate file, we can declare a JavaScript object with different properties and methods.

Step 1: Creating a local module with filename Welcome.js
    const welcome = {
    sayHello : function(){console.log("Hello Students");},
    currTime : new Date().toLocaleDateString(),
    companyName :”SBI"
    }
    module.exports = welcome
Explanation: Here, we declared an object ‘welcome’ with a function sayHello and two variables currTime and companyName. We use the module.export to make the object available globally.

Part 2: In this part, use the above module in app.js file.
    var local = require("./Welcome.js");
    local.sayHello();
    console.log(local.currTime);
    console.log(local.companyName);
Explanation: Here, we import our local module ‘sayHello’ in a variable ‘local’ and consume the function and variables of the created modules.

Output:
    Hello Students
    13/1/2024
    SBI

Module.Exports

    • The module.exports is a special object which is included in every JavaScript file in the Node.js application by default.
    • The module is a variable that represents the current module, and exports is an object that will be exposed(showing) as a module.
    • So, whatever you assign to module.exports will be exposed as a module.
    • Let's see how to expose different types as a module using module.exports.

Export Literals

    As mentioned above, exports is an object. So it exposes whatever you assigned to it as a module. For example, if you assign a string literal then it will expose that string literal as a module.
    The following example exposes simple string message as a module in Message.js.
      //Message.js
      module.exports = 'Hello world';

    Now, import this message module and use it as shown below.
      //app.js
      var msg = require('./Messages.js');
      console.log(msg);


    Run the above example and see the result, as shown below.
    C:\> node app.js
    Hello World

Export Object

The exports is an object. So, you can attach properties or methods to it. The following example exposes an object with a string property in Message.js file.

    //Message.js
    exports.SimpleMessage = 'Hello world';
    //or
    module.exports.SimpleMessage = 'Hello world';

In the above example, we have attached a property SimpleMessage to the exports object. Now, import and use this module, as shown below.

    //app.js
    var msg = require('./Messages.js');
    console.log(msg.SimpleMessage);

In the above example, the require() function will return an object
{ SimpleMessage : 'Hello World'}
and assign it to the msg variable. So, now you can use msg.SimpleMessage.

No comments:

Post a Comment