Swastik Yadav

S Y

Navigate back to the homepage

NodeJS - JavaScript powering the backend

Swastik Yadav
July 30th, 2021 · 2 min read

Hello Everyone,

In this post we will go through an introduction of NodeJS. It is built on Chrome’s V8 JS engine. Basically NodeJS allows us to use JavaScript to build servers and backend applications.

NodeJS is a JavaScript run time environment. It is the way to run JavaScript outside the browser.

Differences between browser and node.js environment.

NodeJS image

Globals in NodeJS

In NodeJS there is no window, because there is no browser, so there is no window object.

But there are global variables, and here are some most commonly used global variables in NodeJS.

  • __dirname: Path to current directory.
  • __filename: file name.
  • require: function to use modules (CommonJS).
  • module: info about current module (file).
  • process: info about env where the program is being executed.

Modules are just separated scripts and files, there are several built in modules in NodeJS. Let’s cover the most popular ones.

  • OS module
  • PATH module
  • FS module
  • HTTP module

OS Module

OS module provides information about the operating system. Here are some examples.

1const os = require('os');
2
3const currentOS = {
4 userInfo: os.userInfo(),
5 name: os.type(),
6 release: os.release(),
7 totalMem: os.totalmem(),
8 freeMem: os.freemem(),
9}
10
11console.log(currentOS);

Path Module

Path module provides functions and information for the file paths.

1const require("path");
2
3console.log(path.sep);
4// consoles the folder separator ("/").
5
6const filePath = path.join("/content", "subfolder", "test.txt");
7// Joins the path of the given folder and files ("/content/subfolder/test.txt").
8
9const base = path.basename(filePath);
10// Gives the base of the given file path.
11
12const absolutePath = path.resolve(__dirname, "content", "subfolder", "test.txt");
13// This joins and returns the absolute file path.

FS Module

FS module provides functions and info about the file system. This mainly helps us to read and write files.

There are two ways to use FS module:

  • Sync: Reads and writes the file synchronously.
  • Async: Reads and writes the file asynchronously using callbacks.
1/* Sync Example */
2const { readFileSync, writeFileSync } = require("fs");
3
4const fileContent = readFileSync("./content/first.txt", "utf8");
5console.log(fileContent); // consoles the content of given file.
6// readFileSync reads the content of the given file synchronously.
7
8writeFileSync(
9 "./content/result-sync.txt",
10 `Here is the result: ${fileContent}`
11);
12// writeFileSync writes the given content to the given file. And creates the file if it does not exists.
13
14/* Async Example */
15const { readFile, writeFile } = require("fs");
16
17readFile("./content/first.txt", "utf8", (err, result) => {
18 if (err) {
19 console.log(err);
20 return;
21 }
22 console.log(result);
23});
24
25writeFile(
26 "./content/result-sync.txt",
27 `Here is the result: ${fileContent}`,
28 (err, result) => {
29 if (err) {
30 console.log(err);
31 return;
32 }
33 console.log(result);
34 }
35);

HTTP Module

This module let’s us make Http request in NodeJS to transfer data over Http. HTTP module creates an HTTP server that listens to server ports and gives a response back to the client.

1const http = require('http')
2
3const server = http.createServer((req, res) => {
4 if (req.url === '/') {
5 res.end('Welcome to our home page')
6 } else if (req.url === '/about') {
7 res.end('Here is our short history')
8 } else {
9 res.end(`
10 <h1>Oops!</h1>
11 <p>We can't seem to find the page you are looking for</p>
12 <a href="/">back home</a>
13 `)
14 }
15})
16
17server.listen(5000)

NodeJS Event Loop

With help of event loop we can offload some time consuming operations.

The event loop is what allows Node.js to perform non-blocking I/O operations — despite the fact that JavaScript is single-threaded — by offloading operations to the system kernel whenever possible.

For example without the event loop if a user requests for a time consuming operation, other users will be blocked till the operation is completed.

And with the event loop, the operation is offloaded and executed only when completed, hence other users are not blocked.

More detail on NodeJS event loop: https://nodejs.dev/learn/the-nodejs-event-loop

1const { readFile, writeFile } = require('fs');
2
3console.log('started first task');
4// CHECK FILE PATH!!!!
5readFile('./content/first.txt', 'utf8', (err, result) => {
6 if (err) {
7 console.log(err);
8 return
9 }
10 // console.log(result)
11 console.log('completed first task')
12})
13console.log('starting next task');
14
15// Result:
16// started first task
17// starting next task
18// completed first task

Event-driven programming

In event-driven programming, we listen for specific events and register functions that will execute in response to those events. So, once our event takes place callback function fires.

Event objects have many methods, the two most used are:

  • on: listen for an event.
  • emit: emit an event.
1const EventEmitter = require("events");
2
3const customEmitter = new EventEmitter();
4
5customEmitter.on("response", (name, id) => {
6 console.log(`data recieved: ${name} with id: ${id}`);
7});
8
9customEmitter.emit("response", "john", 34);

A bunch of built-in modules rely heavily on this concept of events.

Streams

In NodeJS streams are used to read and write sequentially. Streams help us handle and manipulate streaming data, for example, continuous source or a big file stream.

There are four types of streams:

  • Writeable: To write data sequentially.
  • Readable: To read data sequentially.
  • Duplex: To both read and write data sequentially.
  • Transform: To modify data while reading or writing.
1const { createReadStream } = require('fs')
2
3// default 64kb
4// last buffer - remainder
5// highWaterMark - control size
6// const stream = createReadStream('./content/big.txt', { highWaterMark: 90000 })
7// const stream = createReadStream('../content/big.txt', { encoding: 'utf8' })
8const stream = createReadStream('./content/big.txt')
9
10stream.on('data', (result) => {
11 console.log(result)
12})
13stream.on('error', (err) => console.log(err))

HTTP stream example.

1const http = require("http");
2const fs = require("fs");
3
4http.createServer(function(req, res) {
5 // const text = fs.readFileSync('./content/big.txt', 'utf8')
6 // res.end(text)
7
8 const fileStream = fs.createReadStream("./content/big.txt", "utf8");
9 fileStream.on("open", () => {
10 fileStream.pipe(res);
11 })
12 fileStream.on("error", (err) => {
13 res.end(err);
14 })
15}).listen(5000);

Basic NodeJS server app setup.

Here is a basic server setup with core NodeJS.

1const http = require('http')
2const { readFileSync } = require('fs')
3
4// get all files
5const homePage = readFileSync('./navbar-app/index.html')
6const homeStyles = readFileSync('./navbar-app/styles.css')
7const homeImage = readFileSync('./navbar-app/logo.svg')
8const homeLogic = readFileSync('./navbar-app/browser-app.js')
9
10const server = http.createServer((req, res) => {
11 // console.log(req.method)
12 const url = req.url
13 console.log(url)
14 // home page
15 if (url === '/') {
16 res.writeHead(200, { 'content-type': 'text/html' })
17 res.write(homePage)
18 res.end()
19 }
20 // about page
21 else if (url === '/about') {
22 res.writeHead(200, { 'content-type': 'text/html' })
23 res.write('<h1>about page</h1>')
24 res.end()
25 }
26 // styles
27 else if (url === '/styles.css') {
28 res.writeHead(200, { 'content-type': 'text/css' })
29 res.write(homeStyles)
30 res.end()
31 }
32 // image/logo
33 else if (url === '/logo.svg') {
34 res.writeHead(200, { 'content-type': 'image/svg+xml' })
35 res.write(homeImage)
36 res.end()
37 }
38 // logic
39 else if (url === '/browser-app.js') {
40 res.writeHead(200, { 'content-type': 'text/javascript' })
41 res.write(homeLogic)
42 res.end()
43 }
44 // 404
45 else {
46 res.writeHead(404, { 'content-type': 'text/html' })
47 res.write('<h1>page not found</h1>')
48 res.end()
49 }
50})
51
52server.listen(5000)

That’s it for the basics of core NodeJS. If you found this helpful, please do share and subscribe to my newsletter below or here.

Thank You!

More articles from Swastik Yadav

Intro to object oriented programming in JavaScript

Introduction to object oriented programming. Learn how to create and work with objects.

July 23rd, 2021 · 3 min read

Working with modules in JavaScript

Introduction to modules in JavaScript and export / import.

July 16th, 2021 · 1 min read

DiaryOfADev, Success stories of underdog developers.

Every week we share an underdog developer's story and a deep dive into a programming concept.

© 2021–2024 Swastik Yadav
Link to $https://github.com/SwastikyadavLink to $https://www.linkedin.com/in/swastikyadav/