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 Name | Description |
---|---|
http | HTTP Server |
os | Operating System |
fs | File I/O |
url | URL Resolution and Parsing |
path | File and Directory paths |
net | Networking |
dns | DNS lookup |
events | Event Emitters and Listeners |
stream | Interface 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.
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.
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
Nothing yet..be the first to share wisdom.