NodeJS 8 from Scratch — Part 1

Anuj Baranwal
4 min readJul 12, 2018

--

In this series, we will be discussing about

  • nodeJS from basics
  • the essentials that is needed to build nodeJS applications
  • understand how node works
  • the two important questions — What is node? and Why node?

Before we dive in, let’s just quickly set up node. The setup for node could not be any more easy. Just have to download the latest installer(v8.*.*) from https://nodejs.org/en/ and run it and accept all the defaults as of now.

Once the node is successfully installed, we can verify it by running the command in the terminal —

node -v -> will output the version installed in the system. node is the command and -v is the flag for version.

Let’s divide the official definition of nodeJS in three parts —

Node is a javascript runtime built on top of chrome’s v8 javascript engine

  • Earlier, we were able to run javascript only inside the browser. But with node, we can run javascript on machine as a standalone process. This allows us to run javascript applications outside the context of the browser
  • some of the major differences between running javascript in node and browser are —
    browser has window, node has global
    browser has document, node has process

Node is an event driven, non blocking i/o model which makes it light weight and efficient

  • the event loop is what keeps a nodeJS application running. It is a set of phases that are traversed continuously with specific tasks for each phase
  • i/o refers primarily to interaction with system’s disk and network supported by libuv(non-javascript operations) — fetching from a database, writing to a database, etc. and it all works in an event driven mechanism, meaning, that a request is being initiated to read from a database, other stuffs in the app are unblocked, and when the database read is completed, the node event driven arch gets notified about it and then it completes the callback that it has been assigned for it(https://medium.com/the-node-js-collection/what-you-should-know-to-really-understand-the-node-js-event-loop-and-its-metrics-c4907b19da4c)
  • blocking is when the execution of additional javascript in the nodeJS process must wait until a non-javascript operation completes
  • in nodeJS, all such non-blocking operations provides a async version, and accept callback functions
  • nodeJS is single threaded, so concurrency refers to the event loop’s capacity to execute javascript callback functions after completing other work
  • any code that is expected to run in a concurrent manner must allow the event loop to continue running as non-javascript operations, like i/o, are occurring
  • never mix blocking and non-blocking code
const fs = require('fs');
fs.readFile('/file.md', (err, data) => {
if (err) throw err;
console.log(data);
});
fs.unlinkSync('/file.md');

In the above example, fs.unlinkSync() is likely to be run beforefs.readFile(), which would delete file.md before it is actually read.

Better Approach —

const fs = require('fs');
fs.readFile('/file.md', (readFileErr, data) => {
if (readFileErr) throw readFileErr;
console.log(data);
fs.unlink('/file.md', (unlinkErr) => {
if (unlinkErr) throw unlinkErr;
});
});

It is important to understand the difference between blocking and non_blocking through an example so that we can clearly understand why nodeJS is actually doing a good job in such a case?

The code is just some random cooked up code, so need not run this. It is just for explanation.

in blocking.js

var getUser = getUserSync('./user');console.log('Starting User1'); // small black box(about 1s - just an assumption)
var user1 = getUser('123'); // big black box(about 4s)
console.log(user1); // 1s
console.log('Starting User2'); // 1s
var user2 = getUser('321'); // 4s
console.log(user2); // 1s
var sum = 1 + 2; // 1s
console.log(sum); // 1s

This is an example of a blocking call. Even to get a sum simple printed, it requires 13 seconds before it can actually print it. Let’s see how we can improve upon it using the non-blocking i/o model of nodeJS

in non_blocking.js

var getUser = getUser('./user');console.log('Starting User1'); // small black box(about 1s - just an assumption)
getUser('123', function (user1) {
console.log(user1);}); // 1s to initiate the request. It's a non-blocking I/O call and therefore the event loop will execute the callback once the event is received
console.log('Starting User2'); // 1s
getUser('123', function (user2) {
console.log(user2);}); // 1s
var sum = 1 + 2; // 1s
console.log(sum); // 1s

This is an example of a non-blocking call. To get a simple sum printed, it requires 5 seconds before it can actually print it. This happened because now we are not waiting on the I/O anymore.

Let’s create our first node example to print a simple Hello World on console.

in hello_world/app.js

console.log('Hello World');

To execute the code in node, type —

node app.js

Lastly, let’s talk a bit about npm which is the largest package manager for javascript and also the world’s largest software registry. If we can think of anything in general that is required to be used in our project, there will be someone definitely who must have put the package out there in npmjs.com.

So, that’s it for the first part. Here, we discussed about —

  • the theoretical details of nodeJS
  • setting up node
  • event loop
  • blocking vs non-blocking
  • i/o
  • npm

Stay tuned for part 2 where we will start building a real app in nodeJS. See ya later. :)

Part 2 — https://medium.com/@anujbaranwal/nodejs-8-from-scratch-part-2-3035f8f46b09

Part 3 — https://medium.com/@anujbaranwal/nodejs-from-scratch-part-3-20956ec252a3

Part 4 — https://medium.com/@anujbaranwal/nodejs-from-scratch-part-4-d0aadf019c79

Part 5 — https://medium.com/@anujbaranwal/nodejs-8-from-scratch-part-5-3d3e3a84b64

Part 6.1 — https://medium.com/@anujbaranwal/nodejs-8-from-scratch-part-6-1-api-development-5dee11785d62

Part 6.2 — https://medium.com/@anujbaranwal/nodejs-8-from-scratch-part-6-2-api-development-f92f76eb3521

Part 6.3 — https://medium.com/@anujbaranwal/nodejs-8-from-scratch-part-6-3-api-development-9b046fed7364

Part 6.4 — https://medium.com/@anujbaranwal/nodejs-8-from-scratch-part-6-4-api-development-38d600a35ad9

--

--

Anuj Baranwal

Full Stack Web Developer @AdobeSystems Bangalore. Sometimes I code, I draw, I play, I edit and write