Node.js Exercises

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


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 ''.

var http = require('http');
host: '',
method: 'GET',
path: "/"
}, function(response) {
response.on("readable", function() {

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


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-


Output of the above code

nodejs parse url

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


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

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



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:

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"


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"
delete user.last_name;
Output of the above code:
{ first_name: 'John',
  last_name: 'Smith',
  age: '38',
  department: 'Software' }
{ first_name: 'John', age: '38', department: 'Software' }

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


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;
        console.log( dirTree );

8. How does node connect to database?


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"
    if(err) {
        console.log('Error connecting to Db');
    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']


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 => {
Output of the above code:

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


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) {
  console.log('Line number ' + lineno + ': ' + line);

11. How does node JS connect to MongoDB database?


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

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


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

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


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');
    // file not presenet
    var data = fs.readFileSync('demo.html');
} catch (err){

Read more articles

General Knowledge

Learn Popular Language