NodeJS API – Important Libraries

In this blog we will see some of the most useful and frequency used functions of nodejs api.

NodeJS Files System

Nodejs provide easy function for file system access. It provide lot of helper functions to read/write files, read/create/delete directory and many other file system related operations. All functions can be found here http://nodejs.org/api/fs.html

We will see an example code to delete a file.

var fs = require('fs');  //require the file system module

fs.unlink('/tmp/hello', function (err) {
  if (err) throw err;
  console.log('successfully deleted /tmp/hello');
});

NodeJS Crypto

Nodejs crypto provides easy functions to hashes, ciphers, hmacs and other cryptographic operations.

Lets see a code to generate md5 hash.

var crypto = require('crypto');
var md5Hash = crypto.createHash('md5');
md5Hash.update('Hello World');
var hash = md5Hash.digest('hex');

Similar code can be used to sha1 hash and hmac as well. Detailed documentation can be seen here http://nodejs.org/api/crypto.html

NodeJS Child Process

Nodejs provide child process library to spawn or execute programs on command line.

var exec = require('child_process').exec,child;
var execStr = 'php run.php';
child = exec(execStr, function (error, stdout, stderr) {
    if (error) {
        console.log('exec error: ' + error);
    } else {
        console.log(stdout);
    }
});

More details on this can be found here http://nodejs.org/api/child_process.html

NodeJS URL, Query String

Nodejs provide easy functions to parse and format URLs. More details can be seen here
http://nodejs.org/api/url.html and http://nodejs.org/api/querystring.html