Skip to content

Exercises

Introduction

Create these exercises with Node.js without creating any real Node.js project. Create a just one or more JavaScript files to complete each exercises.

These exercises are optional to do, but they contain a lot of useful information about Node.js programming. Exercise solutions are available in the same page, but remember try to code them first by yourself.

Exercise 01 - Testing Node.js setup

Test that you have Node.js installed correctly to your computer. Create a one JavaScript file and use a console.log() to print some text string to the console.

solution - try to code it by yourself

1
2
// exercise01.js
console.log("Just a testing!")
1
2
> node exercise01.js
Just a testing!

Exercise 02 - Own functions

Create a sum, substraction, multiplication and division functions which takes two parameters and return calculation result. Call those functions from your application and show results.

solution - try to code it by yourself

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// exercise02.js
const sum = (number1, number2) => {
  return number1 + number2
}
const subs = (number1, number2) => {
  return number1 - number2
}

const mult = (number1, number2) => {
  return number1 * number2
}

const div = (number1, number2) => {
  return number1 / number2
}

let number1 = 10
let number2 = 2

console.log(`${number1} + ${number2} = ${sum(number1,number2)}`)
console.log(`${number1} - ${number2} = ${subs(number1,number2)}`)
console.log(`${number1} * ${number2} = ${mult(number1,number2)}`)
console.log(`${number1} / ${number2} = ${div(number1,number2)}`)
1
2
3
4
5
> node exercise02.js
10 + 2 = 12
10 - 2 = 8
10 * 2 = 20
10 / 2 = 5

Exercise 03 - Own module

Create own calculator module and move above functions inside it. Use your own made module in your main app and call functions.

solution - try to code it by yourself
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// calculator.js
const sum = (number1, number2) => {
  return number1 + number2
}

const subs = (number1, number2) => {
  return number1 - number2
}

const mult = (number1, number2) => {
  return number1 * number2
}

const div = (number1, number2) => {
  return number1 / number2
}

module.exports = {
  sum, subs, mult, div
}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// exercise03.js
const calculator = require('./calculator')

let number1 = 10
let number2 = 2

console.log(`${number1} + ${number2} = ${calculator.sum(number1,number2)}`)
console.log(`${number1} - ${number2} = ${calculator.subs(number1,number2)}`)
console.log(`${number1} * ${number2} = ${calculator.mult(number1,number2)}`)
console.log(`${number1} / ${number2} = ${calculator.div(number1,number2)}`)
1
2
3
4
5
> node exercise03.js
10 + 2 = 12
10 - 2 = 8
10 * 2 = 20
10 / 2 = 5

Exercise 04 - JavaScript and looping - part 1

Create an array with words and make a sentence by looping an array. Print created sentence to the console.

For example:

  • array with words: "Looping", "array", "is", "simple", "at, "Node.js!"
  • will print "Looping array is simple at Node.js!"
solution - try to code it by yourself

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// exercise04.js
const message = ""
const words = ["Looping", "an", "array", "is", "simple", "at", "Node.js!"]

// easy but this is not asked - you need to use a loop
// console.log(words.join(" "))

const sentence = words.reduce( (result, word) => { 
  return result + ' ' + word 
})

console.log(sentence)
1
2
> node exercise04.js
Looping an array is simple at Node.js!

Look: reduce

Exercise 05 - JavaScript and looping - part 2

Create a function which will take a array of number as a parameters. Function should return a calculated sum. Call your function from the main application and display a sum. Your sum function should return a zero, if your array doesn't has any numbers.

Try to use reduce in your solution.

solution - try to code it by yourself

1
2
3
4
5
6
7
8
const sum = (array) => {
  return array.reduce( (total, number) => { 
    return total + number 
    }, 0)
}

const array = [1,2,3,4,5,6,7,8,9,10]
console.log(sum(array))
1
2
> node exercise05.js
55

Exercise 06 - Command line parameters

Create an application which will return a randomized integer values in an array.

Application will take a command line parameter in following formula:

1
> node exercise.06 RANDOMIZED_NUMBERS_COUNT MIN_VALUE MAX_VALUE

Usage will be printed if parameter values are incorrect. Note that the first argument is in the third position of the array process.argv[2].

Example:

1
2
3
4
5
> node exercise06.js 10 1 100
[1,7,4,3,8,54,33,12,45,88]

> node exercise06.js 
Usage: exercise06.js RANDOMIZED_NUMBERS_COUNT MIN_VALUE MAX_VALUE
solution - try to code it by yourself

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// exercise06.js
const path = require("path")

if (process.argv.length <= 4) {
  console.log("Usage: " + path.basename(__filename) + " RANDOMIZED_NUMBERS_COUNT MIN_VALUE MAX_VALUE")
  process.exit(-1)
}

if (
  isNaN(process.argv[2]) || isNaN(process.argv[3]) || isNaN(process.argv[4]) ||
  process.argv[2] <= 0 || process.argv[3] >= process.argv[4]
) {
  console.log("Usage: " + path.basename(__filename) + " RANDOMIZED_NUMBERS_COUNT MIN_VALUE MAX_VALUE")
  process.exit(-1)

}

// params is string, convert to numbers
let count = Number(process.argv[2])
let min = Number(process.argv[3])
let max = Number(process.argv[4])

const createArray = () => {
  let result = []

  for (let i = 0; i < count; i++ ) {
    result.push(getRandomInt(min, max))
  } 
  return result
}

const getRandomInt = (min, max) => {
  return Math.floor(Math.random() * (max - min  + 1)) + min
}

const array = createArray()
console.log('Randomized numbers: ' + array)
1
2
> node exercise06.js 10 1 100
Randomized numbers: 45,22,48,22,23,21,13,72,49,60

Exercise 07 - Callback functions

First get familiar with a callbacks.

Create a following small application with a callbacks.

1
2
3
4
5
6
7
8
9
const myFunctionWithCallback = (p1, p2, callback) => {
  return callback(p1, p2)
}

const myFunc = (p1, p2) => `Pizza with ${p1} and ${p2}`

const result = myFunctionWithCallback('ham', 'cheese', myFunc)

console.log(result)
1
2
> node exercise07.js
Pizza with ham and cheese

Now try to think what is happening, which order and why.

solution - try to code it by yourself

Line 1 myFunctionWithCallback will be defined

Line 5 myFunc will be defined

Line 7 myFunctionWithCallback will be called with parameters

Line 2 myFunc will be called with parameters

Line 5 myFunc will return 'Pizza with hame and cheese' string to Line 2

Line 7 myFunctionWithCallback will return value to result

Line 9 result will be printed to the console

Exercise 08 - Asynchronous programming

This exercise has an introduction to the asynchronous programming. See the below example to simulate asynchronous execution with callbacks.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
const print = (str, taskTime) => {
  setTimeout(function() {
    console.log(`${str} finished!`)
  }, taskTime)
}

const execute = (str, taskTime, callback)  => {  
  callback(str, taskTime)
}

console.log("Task1 to execution...")
execute('Task1', 2000, print)

console.log("Task2 to execution...")
execute('Task2', 2000, print)

console.log("Task3 to execution...")
execute('Task3', 500, print)

console.log("Last code line executed!")

Now try to think what is happening, which order and why.

solution - try to code it by yourself

Code will print the following to the console:

1
2
3
4
5
6
7
Task1 to execution...
Task2 to execution...
Task3 to execution...
Last code line executed!
Task3 finished!
Task1 finished!
Task2 finished!

setTimeout function will have different waitTimes to simulate task taking time. Task2 will be finished first because it has the shortest waitTime.

It is similar than I/O functions in Node.js, because there are some wait time before tasks are ready. In a real web app you don’t know exactly how long time parsing for example remote JSON data takes or read data from the database.

Exercise 09 - Handling files tutorial

The fs module enables interacting with the file system from the Node.js application.

To use this module:

1
const fs = require('fs')

Create input.txt file and store Sample text line in the file. string inside it.

1
2
// input.txt
Sample text line in the file.

You can read the file with readFile function. (error, data) defines a callback function which will be called after a file reading has been finished.

1
2
3
4
5
6
fs.readFile('input.txt', (error, data) => {
   if (error) console.error(error)
   else console.log(data.toString())
})

console.log("Program ended")

Above programming will print the following lines to the console. Note how Line 6 will be called before the callback function will be called and line 2 or 3 has been executed.

1
2
Program ended
Sample text line in the file.

Note

fs simply provides a wrapper for the standard file operations, like:

  • fs.readFileSync() to read files synchronously
  • fs.readFile() to read files asynchronously
  • fs.watch() for watching changes in files
  • fs.exists() for checking that file exist
  • fs.open() for opening the file
  • fs.stat() for getting file attributes
  • fs.read() for reading chuck of data from the file
  • fs.writeFile() for writing to file
  • fs.close() for closing the file

Exercise 10 - Read a file and calculate a sum of integers

Create an application which reads a numbers from a text file and calculates a sum. Numbers are separated with commas in a text file.

1
1,3,4,6,10,12
solution - try to code it by yourself

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
const fs = require('fs')

const sum = (array) => {
  return array.reduce( (total, number) => { 
    return total + Number(number)
    }, 0)
}

fs.readFile('input.txt', (error, data) => {
  if (error) console.error(error)
  else {
    let array = data.toString().split(',')
    console.log(sum(array))
  }
})

console.log('Reading file and calculate a sum...')
1
2
Reading file and calculate a sum...
36

Exercise 11 - Write a text to the file

Create an application which takes a string as a parameter and write string to the file.

1
> node exercise11.js 'Text to written to the file.'
1
2
Saving text to file...
The file has been saved!

Open your saved text file to see that saving has been done successfully.

solution - try to code it by yourself

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
const fs = require('fs')
const path = require('path')

if (process.argv.length <= 2) {
  console.log("Usage: " + path.basename(__filename) + " 'Text to written to the file.'")
  process.exit(-1)
}

var textToWrite = process.argv[2]

fs.writeFile('output.txt', textToWrite, err => {
  if (err) console.error(error)
  else console.log('The file has been saved!')
})

console.log('Saving text to file...')
1
> node exercise11.js 'Text to written to the file.'
1
2
Saving text to file...
The file has been saved!
1
2
> more output.txt
Text to written to the file.

Exercise 12 - JavaScript Ninja

Create a text file which describes your knowledge of different parts of the JavaScript. Figure out a few ones and just type those in the text file with the following format:

1
JavaScript knowledge:integer_value

For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
Variables:5
Data types:4
Arrays:5
Basic operations:4
Loops:5
Functions:3
Classes:5
Objects:4
Methods:4
Recursion:3
Scope:5
Closure:4
Prototype:4
Error handling:5
Async operations:5
Modules:3

Create an application which loads a text file and displays information to the console.

1
2
3
4
5
Knowledge of Variables  : 5
Knowledge of Data types : 4
// etc.. and finally show a average of the above ones

Your JavaScript Ninja value is : 3.27
solution - try to code it by yourself

Haha... sorry there is no answer for this one. Code it by yourself ;-)

Exercise 13 - Events with EventEmitter

Much of the Node.js core API is built around an asynchronous event-driven architecture in which certain kinds of objects called emitters emit named events that cause function objects listeners to be called.

For instance: a net.Server object emits an event each time a peer connects to it; a fs.ReadStream emits an event when the file is opened; a stream emits an event whenever data is available to be read.

This we have noticed in earlier execises already - hopefully!

All objects that emit events are instances of the EventEmitter class.. So, you can create a emitter.

1
2
const events = require('events')
const emitter = new events.EventEmitter()

These emitter objects expose an eventEmitter.on() function that allows one or more functions to be attached to named events emitted by the object.

For example something_happened event

1
2
3
emitter.on('something_happened', () => {
  console.log('Something nice happened!')
})

and something_else_happened event

1
2
3
emitter.on('something_else_happened', () => {
  console.log('Oh no - what happend?!?!')
})

At any point in the lifecycle of emitter objects, you can use the emit function to emit any named event you want.

1
2
emitter.emit('something_happened')
emitter.emit('something__else_happened')

Will print:

1
2
Something nice happened!
Oh no - what happend?!?!

Read more: EventEmitter

Ok and now the exercise

Let's say that Lady Gaga is keeping a concert. Create an application which displays a text OMG - Lady Gaga start singing! when the application is launched. After a some point of time (for example after 5 seconds) display a text WOW - It was the best concert in my life... to the console. Use EventEmitter in your solution.

Bonus: Show a NICE - fireworks! text in every one second.

Example

1
2
3
4
5
6
OMG - Lady Gaga start singing!
NICE - fireworks!
NICE - fireworks!
NICE - fireworks!
NICE - fireworks!
WOW - It was the best concert in my life...
solution - try to code it by yourself
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
const events = require('events')
const concertEmitter = new events.EventEmitter()

const singer = "Lady Gaga"
let fireworksInveralId

concertEmitter.on('start', (singer) => {
  console.log(`OMG - ${singer} start singing!`)
  // stop singing
  setTimeout( () => {
    concertEmitter.emit('finished')
  }, 5000) 
  // start fireworks
  fireworksInveralId = setInterval( () => {
    concertEmitter.emit('fireworks')
  }, 1000) 
})

concertEmitter.on('fireworks', function () {
  console.log('NICE - fireworks!')
})

concertEmitter.on('finished', function () {
  console.log('WOW - It was the best concert in my life...')
  clearInterval(fireworksInveralId)
})

concertEmitter.emit('start', singer)

Note

Node.js allows us to create and handle custom events easily by using events module and EventEmitters.

To learn more - here is a one good deep level example to follow: Using Event Emitters in Node.js @ digitalocean

Exercise 14 - Web Server Tutorial

You can create a web server with http module.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
const http = require('http')

const hostname = '127.0.0.1'
const port = 3000

const server = http.createServer((req, res) => {
  res.statusCode = 200
  res.setHeader('Content-Type', 'text/plain')
  res.end('Hello World!')
})

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`)
})

Write above code and start your server.

1
2
> node exercise14.js
Server running at http://127.0.0.1:3000/

Try it from your browser and you should see 'Hello World!' text in your browser.

Modify your code to return HTML content. You migth may need to stop and start your server again. Just click CTRL-C to stop server running and run your app again.

1
2
  res.setHeader('Content-Type', 'text/html')
  res.end('<h1>Hello World!</h1>')

Exercise 15 - Web Server Counter App

Create a Node.js server application which can be used from the web browser.

Requirements:

  • Application should store a total requests made to this application.
  • Application will respond this request made integer value to the client.
  • Store count number to the text file.

Example:

Browser is used to http://localhost:3000/ and application prints to document

1
Request counter value is 1

Web page is refreshed, and application prints to document

1
Request counter value is 2

Note

Don't worry if you counter value is increased more than one by time. That is normal - your browser makes more than one call. Most browsers make a call to grab /favicon.ico for example.

solution - try to code it by yourself

Haha... sorry there is no answer for this one. Code it by yourself ;-)