Node.js Exercises

1. Write a node.js program for making external http calls.

Solution

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

2. Write a program in node.js to parse the given url.

http://www.etutorialspoint.com/index.php/nodejs/node-js-filesystem

Solution

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

nodejs parse url



3. Write a program to check request header for cookies.

Solution

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

4. Write a node.js program to replace two or more a's with the letter b on the given string using Regular Expression.

aaewewedsdewddsxac

Solution

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"));
Output of the above code:
bewewedsdewddsxac

5. There is a given object, write node.js program to print the given object's properties, delete the second property and get length of the object.

var user = {
first_name: "John",
last_name: "Smith",
age: "38",
department: "Software"
};

Solution

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);
Output of the above code:
{ first_name: 'John',
  last_name: 'Smith',
  age: '38',
  department: 'Software' }
4
{ first_name: 'John', age: '38', department: 'Software' }
3




6. Write a node.js program to get files or directories of a directory in JSON format.

Solution

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

8. How does node connect to database?

Solution

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) { 
});




9. How do you iterate over the given array in node.js?

['fish', 'crab', 'dolphin', 'whale', 'starfish']

Solution

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);
});
Output of the above code:
fish
crab
dolphin
whale
starfish

10. How to read a file line by line using node.js ?

Solution

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

11. How does node JS connect to MongoDB database?

Solution

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();
});




12. How do you zip a file in node.js?

Solution

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

13. How do you use try catch blocks in node.js?

Solution

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){
    console.log(err);
}




Read more articles


General Knowledge



Learn Popular Language