Node.js Built-in Modules

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
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');


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) {
   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,

Post a comment


Your Comment

Email (We dont publish it)


Nothing the first to share wisdom.