Saturday, 11 November 2017

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
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

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().

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...