Node.js

Node.js Built-in Modules

Posted on 20th January 2017

Node.js is light-weight and comes with built-in modules (core modules) for basic tasks like file i/o, networking etc. Some of the useful core modules available with Node.js are

Core Module NameDescription
httpHTTP Server
osOperating System
fsFile I/O
urlURL Resolution and Parsing
pathFile and Directory paths
netNetworking
dnsDNS lookup
eventsEvent Emitters and Listeners
streamInterface for streaming data

To include a core module in your program, you need to import it using require() function

 var x = require('module_name');

Example:

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

Now we can look at some code samples using core modules.

Sample Code to display OS Platform

var os = require("os");
// OS platform
console.log('OS Platform : ' + os.platform());

The above code imports os module and uses the os.platform() method to display the OS Platform.

Sample code to check for directory

var fs = require("fs");
fs.stat('samplefolder', function (err, stats) {
   if (err) {
       console.log("Error");
   }
   else {
       if(stats.isDirectory())
          console.log("Directory");
       else
          console.log("Not a Directory");
   }
});

The above code imports fs module. The fs.stat(path, callback) method takes two arguments – the path to the file or directory and a callback function. Since fs.stat() is an asynchronous function, you have to pass a callback function to be executed when it finishes. The callback takes two arguments – err and stats which will be set by the fs.stat() method. The stats object has a stats.isDirectory() method that can be used to check for directories.

Most basic tasks can be performed by using just the core modules. For more advanced tasks, you can use a third-party module or write your own. Many frameworks are also available for rapid development like Express.js, Meteor, Hapi.js, Socket.io

Post a comment

Comments

Nothing yet..be the first to share wisdom.