Node.js Beginner Guide

You don’t have access to this lesson
Please register or sign in to access the course content.

Installing and Setting it up

Node.js is an open-source, cross-platform, back-end JavaScript runtime environment that runs on the V8 engine and executes JavaScript code outside the browser. Node.js helps the developer write code that runs on the server side, making it possible for server-side scripting to be achieved.

Setup

Although Ubuntu provides Node.js in it’s default repository, it is not the latest stable version. So, for setting up the latest stable version of node we install it through the node source.

# Using Ubuntu
curl -fsSL <https://deb.nodesource.com/setup_17.x> | sudo -E bash -
sudo apt-get install -y nodejs

The latest version as of now is 17. For releases look at the node source repository, it also comes with detailed installation guide for other operating systems.

After installation

Now that node is successfully installed on your machine, we go through the next step

Writing First Lines of Code in Node.js

First Lines of Code

create index.js file and write the following code inside here.

console.log("Hello World");

Execution of Written Code

$ node index.js

result after code execution

Simple function invocation

function addition(a, b) {
  console.log(`Addition between ${a} and ${b} is `, (a + b));
}

addition(20, 30);

Again execute the code: node index.js

Package Installation and Usage

Package are code that’s been made publicly available. A package can contain a single file or many files of code. Generally speaking, a package helps you to add some functionality to your application.

Installing a Package

Installing package in the same dirrectory

## installing npm package hello-world-npm
$ npm install hello-world-npm

Installing package globally

## installing npm package globally
$ npm install -g nodemon

Using the installed package in Node.js

Now we see using package in nodejs

## initializing node project
$ npm init -y

$ npm install hello-world-npm

$ touch index.js && code .
const { helloWorld } = require("hello-world-npm");

console.log("Result:", helloWorld());

File: index.js

$ node index.js
Result: Hello World NPM

In above example we are invoking method called helloWorld() which is present in the package hello-world-npm. Invoking this method we get the output Hello World NPM.

Modules in Node.js

what is module in Node.js?

Modules are same as JavaScript libraries. A module is a JavaScript file that contains a bunch of functions, and those functions accomplish some useful task for your application.

There are two types of modules in JavaScript

  • Build-in Modules
  • User defined Modules

Built-in Modules

The are the modules in that can be used without any further installation. They are modules that are in-built in node.

ModulesDescription
bufferUsed to handel Binary data
fsUsed to handle files
httpUsed to make http server
osUsed to get information about the operating system
urlUsed to parse URL strings
tlsUsed to implement TLS AND SSL protocols

They are some of the mostly used modules present in node.

Using the module

For using the module we need to use the require() function with the name of the module wrapped inside it.

const http = require("http");

http.createServer(function (req, res) {
  res.write('Hello Scan Skill');
  res.end();
}).listen(8080);

Here we see that functions and methods present inside the http package by including the package using require() function.

User Defined Modules

We can create modules bu using the exports keyword.

exports.helloWorld = function () {
  return "Hello World";
}

file: hello.js

include the file hello.js in the file that you want to use your modules in.

const hello = require("./hello");

console.log(hello.helloWorld());

file: index.js

## result
Hello World

That is the way we create and use user defined modules in Node.js

HTTP Module

HTTP Module is an built-in module present in Node.js, which helps you to transfer data over HTTP (Hyper Text Transfer Protocol)

HTTP module is used to create HTTP server that listens to a given port and responds back to the clients request. We use the createServer() method to create an HTTP server in Node.js using the HTTP module.

Creating a simple server

const http = require("http");

http.createServer((req, res) => {
  res.write("Hello World");
  res.end();
}).listen(4000);

Handling different Routes

For handling routes we nee to use another built-in module url which is used to parse urls.

const http = require("http");
const url = require("url")

http.createServer((req, res) => {
  const path = url.parse(req.url, true).path;
  if(path === '/') {
    res.write("index page invoked");
    res.end();
  } else if(path === '/contact') {
    res.write("contact page invoked");
    res.end();
  } else {
    res.write("404 file not found only [ / , /contact ] are present");
    res.end();
  }
}).listen(4000);

Including writeHead() to send custom response code

const http = require("http");
const url = require("url")

http.createServer((req, res) => {
  const path = url.parse(req.url, true).path;
  if(path === '/') {
    res.write("index page invoked");
    res.end();
  } else if(path === '/contact') {
    res.write("contact page invoked");
    res.end();
  } else {
    res.writeHead(404); // response code // default is 200
    res.write("404 file not found only [ / , /contact ] are present");
    res.end();
  }
}).listen(4000);

Using Query parameters

for user query params we use url.parse().query

const http = require("http");
const url = require("url");

http.createServer((req, res) => {
  const query = url.parse(req.url, true).query;
  const {firstName, lastName} = query;
  res.write(`First name = ${firstName} and Last name = ${lastName}`)
  res.end();
}).listen(4000);

So, this is the way of using http built-in module of Node.js.

File Handling in Node.js

In Node.js file handling is achieved through fs module

const fs = require("fs");

We are going to look at achieving following things using fs module

  • create a file
  • writing into a file
  • read a file
  • update contents of a file
  • rename a file
  • delete a file

Create file

const fs = require("fs");

fs.open("readme.txt", "w", (err, file) => {
  if(err) throw err;
  console.log("New file created!")
})

New empty file is created called readme.txt.

Write file

const fs = require("fs");

fs.writeFile("readme.txt", "Hello World", (err, file) => {
  if (err) throw err;
  console.log("New content written in file");
});

Read file

const fs = require("fs");

fs.readFile("readme.txt", (err, data) => {
  if (err) throw err;
  console.log(data.toString());
});

It returns data in the form of buffer, so we need to use toString() method to convert it into string.

Update file

We can use two methods to achieve this

  • appendFile() : Appends to the end of line
  • writeFile() : Deletes the content and writes the given data

appendFile()

const fs = require("fs");

fs.appendFile("readme.txt", "\\nHello World 2", (err, file) => {
  if (err) throw err;
  console.log("data appended");
});

writeFile()

const fs = require("fs");

fs.writeFile("readme.txt", "New content", (err, file) => {
  if (err) throw err;
  console.log("data updated");
});

Rename file

const fs = require("fs");

fs.rename("readme.txt", "dontReadMe.txt", (err, file) => {
  if (err) throw err;
  console.log("File Renamed");
});

Delete file

const fs = require("fs");

fs.unlink("dontReadMe.txt", (err, file) => {
  if (err) throw err;
  console.log("File Deleted");
});

Conclusion

In this chapter, we’ve saw a overview on Node.js, and how it works. Also we looked at using modules, packages, handling files.