An Introduction to Nodejs: Overview

When you open the official website of nodejs, it says "Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine", well it doesn't clear much does it?

When JavaScript was created it used to run on the browsers only, i.e. for frontend. Node js is a platform that allows you to run javascript outside of the browser on a computer or a server. i.e. backend

  • One of the main reasons for the popularity of nodejs is that it uses javascript. For the frontend development is necessary for a developer to learn Javascript along with HTML and CSS. So, by using nodejs at the backend the developer doesn't need to learn any other programming language as they would have to learn other languages like python, c#, etc. if nodejs were not used.

  • Nodejs is very fast as it runs on Chrome's v8 engine. Both Javascript and the V8 engine are written using C++. So, the V8 engine is easily able to convert Javascript code into machine code

  • Node js has a very large ecosystem of open source packages(npm). It is the largest package management system in the world.

  • Due to Nodejs' asynchronous event-driven model scalable applications can be built using it.

Modules

A Module in nodejs is just another JS file that contains a set of functions. Modules contain common functionality that can be used anywhere in the app. To use a module it needs to be exported and imported where ever necessary. Example to export a module

const sum = (num1, num2) => num1 + num2;

module.exports = sum;

Example to import a module

const sum = require("./path_to_file");

console.log(sum(2,3));

Nodejs has several built-in modules like file system module, http module, event module, path module, etc. We'll learn about some of them later in the blog.

Events Module

Nodejs contains a module called "events" which is used to handle custom events. The events module contains an EventEmitter class, to handle the custom events we need to create an object of the EventEmitter class and listen to the event on that object. Example of an event

const EventEmitter = require('events');
const event = new EventEmitter();

// event listens on sum event
event.on("sum", (num1, num2) => {
    console.log(num1 + num2);
});

// emits the event sum
event.emit('sum', 2, 3)

In the above example, on() method is used to listen to the event. The on() method contains two arguments:

  1. The first argument is the event that you want the object to listen to.
  2. The second argument is the callback function, that is invoked when the event is triggered.

emit() method is used to trigger the event. The emit() method emits the event passed as the first parameter, the rest are the arguments. The event can be emitted with zero or more arguments.

Readline Module

Readline module allows reading from an input stream one line at a time. To interact with the user you need to create an instance of the readline interface. The interface can be created using the createInterface() method. createInterface() method takes an object which contains two properties. When createInterface() method is executed it returns readline interface object.

const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,  
  output: process.stdout,  
});

rl.question('What is you name?\n', (name) => {
    console.log('my name is: ' + name);
});

In the above example, the object passed to createInterface() method contains two properties input and output property which will take the standard input and standard output streams. The readline Interface object is stored in rl . The readline interface has a method called question(). The first argument in the question() method will be a string, which is the question we want to ask the user, the second argument is the callback function which takes the user input.

File System Module

The file system module allows working with the files i.e it allows creating, reading, updating, deleting the files. There are various other operations that can be performed by using the file system module.

Creating a file

const fs = require("fs");
// create a file
fs.writeFile("abc.txt", "this is a newly created text file", (err) => {
  if (err) {
    console.log(err);
  } else {
    console.log("File succesfully created");
  }
});

In the above example writeFile() method is used to create a file, it takes 3 arguments, the first argument is the name of the file, the second argument is the data that will be written on the file, the third arguments is a callback function.

Renaming a file

fs.rename("abc.txt", "example.txt", (err) => {
  if (err) console.log(err);
  else console.log("succesfully renamed the file");
});

In the above example rename() method is used to rename a file, it takes 3 arguments, the first argument is the name of the file, the second argument is the new name of the file, the third arguments is a callback function.

Deleting a file

fs.unlink("abc.txt", (err) => {
  if (err) console.log(err);
  else console.log("Successfully deletd the file");
});

Similar to files, the file system can be used to work with directories as well.

Readable and Writeable Streams

Readable and Writeable streams are used to read and write data in small chunks. Imagine reading from a file of a very large size, to read the file in one go using readFile() method it will give an error because it'll require free memory equal to the size of the file.

In those cases reading and writing data in streams come in handy. readStream object inherits from the EventEmitter class. So, by using on() method you can listen to the data event.

const fs = require('fs');
const readstream = fs.createReadStream('./example.txt', 'utf8'); //returns readable stream
const writeStream = fs.createWriteStream('.example2.txt');

readstream.on('data', (chunk) => {
    writeStream.write(chunk);
});

In the above example, we're reading from a file example.txt and the writing onto a different file example2.txt. Both processes will go on simultaneously.

Pipes

pipe() method takes a source stream(readablestream) and attaches it to destination stream (writeablestream)

const fs = require('fs');
const readStream = fs.createReadStream('./example.txt', 'utf8');
const writeStream = fs.createWriteStream('./example2.txt'); 
readStream.pipe(writeStream);

In the above example, pipe takes the data from readStream and writes it on the writeStream.

Creating an HTTP Server

The http module has a method createServer() which is used to create a server. The createSever() method takes two arguments request and response, the request object is what the client requests from the server, and the response is the response of the server to the request. The listen() method takes the port number to which the server listens to.

const http = require('http');
const server = http.createServer((req, res) => {
    res.write('Hello world from nodejs'); 
    res.end();
});

server.listen('3000');