Saturday, 11 November 2017

Node.js | Node.js Local Module

Local modules are modules created locally in Node.js application. These modules may include different functionalities of the application in separate files and folders. We can also package it and distribute it via NPM, so that Node.js community can use it.

For example, if we need to connect to MongoDB and fetch data then we can create a module for it, which can be reused in our application.

Writing a Local Module:
Let's write logging module which logs the information, warning or error to the console.

In Node.js, the module should be placed in a separate JavaScript file. So, create a LogFormatter.js file with below code in it.

LogFormatter.js
<!--Step:1 Create an Object with three required methods -->
var log_formatter = {
            info: function (info) {
                console.log('Info: ' + info);
            },
            warning: function (warning) {
                console.log('Warning: ' + warning);
            },
            error: function (error) {
                console.log('Error: ' + error);
            }
};

<!--Step:2 Assign the object to module.exports -->
module.exports = log_formatter

In the above Local module, two major steps are there:

1. We have created an object with three functions,
             info(), warning() and error().

2. We have assigned this object to module.exports. The module.exports exposes a log_formatter object as a module.

The module.exports is a special object which is included in every JS file in the Node.js application by default. Use module.exports or exports to expose a function, object or variable as a module in Node.js.

Loading Local Module:
To use local modules in the application, we need to load it using require() function in the same way as we used for the core modules. However, we need to specify the path of JavaScript file of the module.

TestLogFormatter.js

var logFormatterModule = require('./LogFormatter.js');

logFormatterModule.info('Node.js started');
logFormatterModule.error('Node.js error);


First, it loads the logging module using require() function and specified path where logging module is stored. Logging module is contained in LogFomatter.js file in the root folder. So, we have specified the path './LogFormatter.js' in the require() function. The '.' denotes a root folder.

The require() function returns a log_formatter object because logging module exposes an object in LogFormatter.js using module.exports. Now we can use logging module as an object and call any of its function like logFormatterModule.info() or logFormatterModule.warning() or logFormatterModule.error().

Output:
D:\node>node TestLogFormatter.js
Info: Node.js started
Error: Node.js error

Node.js | Core Modules

Node.js is a lightweight framework. The core modules include bare minimum functionalities of Node.js. These core modules are compiled into its binary distribution and load automatically when Node.js process starts. However, we need to import the core module first in order to use it in our application.

Some of the important core modules in Node.js are listed below:

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

Loading Core Modules
In order to use Node.js core or NPM modules, we first need to import it using require() function.

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 below example demonstrates how to import Node.js http module to create a web server.

Load and use Core http Module
var http = require('http');
var server = http.createServer(function(req, res){
  //write code here
});
server.listen(8080);

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

Node.js | What is a Module in Node.js?

The 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. It is same as JavaScript libraries. It contains a set of functions we want to include in our application.

Module Types
Node.js includes three types of modules:
3. Third Party Modules

Built-in Modules
Node.js has a set of built-in modules which you can use without any further installation.

Include Modules
To include a module, use the require() function with the name of the module:

var http = require('http');

Now our application has access to the HTTP module, and is able to create a server:
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('Hello World!');
}).listen(8080);

Create Your Own Modules
We can create our own modules, and easily include them in our applications. Create a module that returns the current date and time:
exports.myDateTime = function () {
    return Date();
};

Use the exports keyword to make properties and methods available outside the module file. Save above code in a file named as "myModule.js"

Include our Own Module
We can include the module by using the require function in any of our Node.js files.

var http = require('http');
var dt = require('./myModule');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write("Current date is "+dt.myDateTime());
    res.end();
}).listen(8080);

Output: Current date is Sat Nov 11 2017 19:40:17 GMT+0530 (India Standard Time)





Java | How to insert the 100000 records in database using PreparedStatement batch?

Inserting the records one by one will take a lot of time as 100000 execute and commit calls will be required on the PreparedStatment instances.

To avoid the time overhead, we can use the concept of the batch which will insert the 1000 records with one call of executeBatch and commit methods.

1. Create DB connection.
2. Create a query for the prepared statement.
3. Set auto commit false.
4. Prepare statement and add it to batch.
5. If the batch size is multiple of 1000 then commit the database.
6. Repeat step 4 and 5 till the complete data is loaded.
7. Close connection.

Same has been implemented below given method:
public static int uploadFilesData(List<CallDetailDTO> list) {
          
        connection = getConnection();
          
        String query = Constants.INSERT_PREFIX + Constants.TABLE_ROWS + Constants.PREPARED_STMT_VALUE;
        int count = 0;
        try {
             connection.setAutoCommit(false);
             PreparedStatement ps = connection.prepareStatement(query);
             for (CallDetailDTO dto: list) {
                 ps.setString (1,dto.getPartyNumberA());
                 ps.setString (2,dto.getPartyNumberB());
                 ps.setString (3,dto.getCallDate());
                 ps.setString (4,dto.getCallTime());
                 ps.setString (5,dto.getDuration());
                 ps.setString (6,dto.getCellId());
                 ps.setString (7,dto.getLastCellId());
                 ps.setString (8,dto.getCallType());
                 ps.setString (9,dto.getImei());
                 ps.setString (10,dto.getImsi());
                 ps.setString (11,dto.getPpPo());
                 ps.setString (12,dto.getSmsCentre());
                 ps.setString (13,dto.getRoamingNwCied());
                 ps.setString (14,dto.getSheetName());

                 ps.addBatch();

                 if(++count % 1000 == 0) {
                       ps.executeBatch();
                       connection.commit();
                 }
             }
             ps.executeBatch();
             connection.commit();
             ps.close();
             connection.close();
        } catch (SQLException e) {
             System.out.println("SQLException:"+e.getMessage());
        }
        return count;
}

Algorithms | Calculate the power in log(n) complexity in Java

Using divide and conquer

public class PowerUsingDnC {
     public static void main(String[] args) {
           int x = 5;
           int n = 7;

           /** To calculate the power of x^n. */
           int result = power(x,n);
          
           System.out.println(result);
     }

     private static int power(int x, int n) {
           int temp = 1;

           if(n==0) {
                return 1;
           }

           int result = 1;

           /** divide using original power function. */
           temp = power(x, n/2);

           /** conquer using temp value. */
           if(n%2==0) {
                result = temp*temp;
           } else {
                result = temp*temp*x;
           }
           return result;
     }
}
Related Posts Plugin for WordPress, Blogger...