Node.js Exercises With Solutions

Theory of Computation
It is often necessary for a network application to make external HTTP calls. HTTP servers are also often called upon to perform HTTP services for clients making requests. Node.js provides an easy interface for making external HTTP calls. For example, the following code will fetch the front page of 'google.com'.
var http = require('http');
http.request({
host: 'www.google.com',
method: 'GET',
path: "/"
}, function(response) {
response.setEncoding("utf8");
response.on("readable", function() {
console.log(response.read())
});
}).end();
http://www.etutorialspoint.com/index.php/nodejs/node-js-filesystem
Whenever a request is made to an HTTP server, the request object will contain URL property, identifying the targeted resource. This is accessible via the request.url. Node's URL module is used to decompose a typical URL string into its constituent parts. Consider the following figure-
console.log(url.parse("http://www.etutorialspoint.com/index.php/nodejs/node-js-filesystem"));
Output of the above code
Cookies are pieces of content that are sent to a user's web browser. Cookies are small data that are stored on a client side and sent to the client along with server requests. The HTTP header Set-Cookie is a response header and used to send cookies from the server to the user agent. So the user agent can send them back to the server later so the server can detect the user. The given program checks the request header for cookies.
var http = require('http');
var url = require('url');
var server = http.createServer(function(request, response) {
var cookies = request.headers.cookie;
if(!cookies) {
var cookieName = "session";
var cookieValue = "123456";
var expiryDate = new Date();
expiryDate.setDate(expiryDate.getDate() + 1);
var cookieText = cookieName + '=' + cookieValue + ';expires='
+ expiryDate.toUTCString() + ';';
response.setHeader('Set-Cookie', cookieText);
response.writeHead(302, {
'Location': '/'
});
return response.end();
}
cookies.split(';').forEach(function(cookie) {
var m = cookie.match(/(.*?)=(.*)$/);
cookies[m[1].trim()] = (m[2] || '').trim();
});
response.end("Cookie set: " + cookies.toString());
}).listen(8080);

aaewewedsdewddsxac
JavaScript has powerful regular expression support.
A certain number of string functions can take arguments that are regular expressions to perform their work. These regular expressions can either be entered in literal format or as a call to the constructor of a RegExp object. The RegExp object is used for matching text with a pattern.
console.log("aaewewedsdewddsxac".replace(new RegExp("[Aa]{2,}"), "b"));
bewewedsdewddsxac
var user = {
first_name: "John",
last_name: "Smith",
age: "38",
department: "Software"
};
Objects are one of the core workhorses of the JavaScript language, and something you will use all the time. They are an extremely dynamic and flexible data type, and you can add and remove things from them with ease.
var user = {
first_name: "John",
last_name: "Smith",
age: "38",
department: "Software"
};
console.log(user);
console.log(Object.keys(user).length);
delete user.last_name;
console.log(user);
console.log(Object.keys(user).length);
{ first_name: 'John',
  last_name: 'Smith',
  age: '38',
  department: 'Software' }
4
{ first_name: 'John', age: '38', department: 'Software' }
3
JSON (JavaScript Object Notation) is a lightweight, open standard, data-interchange format. It is easy to read and write for humans. It is used primarily to transmit data between web application and server. The given example asynchronously convert directory tree structure into a JavaScript object.
Install with NPM
npm install dir-to-json --save
var dirToJson = require('dir-to-json');
 
dirToJson( "./album", function( err, dirTree ){
    if( err ){
        throw err;
    }else{
        console.log( dirTree );
    }
});
 
 
To connect to MySQL server, we will create a connection with mysql module. So, first include the mysql module, then call the create connection method. Here is the sample code to connect to database.
var mysql = require("mysql");
var con = mysql.createConnection({
    host: "hostname",
    user: "username",
    password: "password",
    database: "database"
});
con.connect(function(err){
    if(err) {
        console.log('Error connecting to Db');
        return;
    }
    console.log('Connection Established');
})
con.end(function(err) { 
});
['fish', 'crab', 'dolphin', 'whale', 'starfish']
Node.js provides forEach()function that is used to iterate over items in a given array.
const arr = ['fish', 'crab', 'dolphin', 'whale', 'starfish'];
arr.forEach(element => {
  console.log(element);
});
fish
crab
dolphin
whale
starfish
Readline Module in Node.js allows the reading of input stream line by line.
The given node.js code open the file 'demo.html' and return the content line by line.
var readline = require('readline');
var fs = require('fs');

var file= readline.createInterface({
  input: fs.createReadStream('demo.html')
});

var lineno = 0;
file.on('line', function (line) {
  lineno++;
  console.log('Line number ' + lineno + ': ' + line);
});
MongoDB is one of the most popular databases used along with Node.js. We need a driver to access Mongo from within a Node application. There are a number of Mongo drivers available, but MongoDB is among the most popular. To install the MongoDB module, run the below command -
npm install mongodb
Once installed, the given code snippet shows you how to create and close a connection to a MongoDB database.
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  console.log("Database created!");
  db.close();
});
Node.js provides Zlib module to zip a file. The given example demonstrates this -
var zlib = require('zlib');
var fs = require('fs');

var gzip = zlib.createGzip();
var r = fs.createReadStream('./demofile.txt');
var w = fs.createWriteStream('./demogzipfile.txt.gz');
r.pipe(gzip).pipe(w);
In the given node.js program, we are using a Try Catch block around the piece of code that tries to read a file synchronously.
var fs = require('fs');
 
try{
    // file not presenet
    var data = fs.readFileSync('demo.html');
} catch (err){