Node.js — What, Why and How

Jack Yeung
Sep 5, 2018 · 3 min read

What is Node.js?

From the original source, Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. To provide clarity, V8 is Google’s open source high-performance JavaScript engine that is used in Google Chrome and Node.js. Node is an asynchronous event driven JavaScript runtime that was created by design to develop scalable network applications. It is a program that enables us to apply javascript outside of the browser.

Node.js runs a single-threaded event loop registered with the system. It in turn handles connections, in which each new connection triggers a JavaScript callback function to execute. Node’s use of callback functions to scale leads to efficient memory-use in handling more connections than other architectures that scale with threads such as Ruby on Rails.

Blocking I/O vs. Non-Blocking I/O

I/O — stand for input/output. An example would be when we make an HTTP request to an API. When it comes to I/O, there are two types — blocking I/O and non-blocking I/O.

In blocking, tasks or functions “block” execution of tasks other than the current one taking place until it is completed; operations are carried out one at a time. In a synchronous blocking example, while reading a file, all other tasks are halted and cannot be executed in parallel during this time. In the below code example, localStorage is an operation that is blocking alert(2) from executing until its own completion.

In non-blocking, tasks and functions can execute parallel to one another at the same time. Using Asynchronous servers made in Node as an example, the servers leverage a single thread to service all requests. The advantage of non-blocking asynchronous operations is that it enables the potential to maximize a single CPU along with improving memory-use efficiency. In the same code example below, alert(3) completed before the fetch.

// Blocking: 1,... 2
alert(1);
var value = localStorage.getItem('foo');
alert(2);

// Non-blocking: 1, 3,... 2
alert(1);
fetch('example.com').then(() => alert(2));
alert(3);
Sourced from flicker

Blocking methods execute synchronously, while non-blocking methods execute asynchronously.

Node Command

Installation of Node.js on a system provides access to a program called Node — it is used to execute JavaScript files.

Let’s say we have a file, greetings.js, with the code content of:

let message = "Hi there adventurers";
console.log(message);

We can run Node from the command line with the following code to execute our program:

$ node greetings.js
Hi there adventurers

Notice that executing the JavaScript file logs the values in our terminal rather than on a browser’s JavaScript console. In Node, the text will be outputted on the process’s standard output stream.

Similar to Ruby’s interactive Ruby (IRB), if you run node without providing a file, the terminal enters a session where you can type JavaScript code and receive instant results.

$ node
> 150 * 100
15000
>["Node", "Node!", "Node!!", "Node!!!"].map((x) => x.toUpperCase())
["NODE", "NODE!", "NODE!!", "NODE!!!"]

Node Modules

Upon installing Node on your computer, you gain access to the npm command. NPM’s main use is fetch, download, and install packages on the computer via npm install.

File System Module

A built-in module that is very often used in Node is the fs (file system) module. It exports functions for working with files and directories.

The blow example shows how the readFile function reads the file and follows with a callback to retrieve the file contents.

let {readFile} = require("fs");
readFile("file.txt", "utf8", (error, text) => {
if (error) throw error;
console.log("The file contains the following: ", text);
});

HTTP Module

Another commonly used module is the http module. This module provides functionality for running HTTP servers and making HTTP requests.

The following code displays how to start an HTTP server:

const {createServer} = require("http");
let server = createServer((request, response) => {
response.writeHead(200, {"Content-Type": "text/html"});
response.write(`
<h1>Why hello there!!!</h1>
<p>You inquired about <code>${request.url}</code></p>`);
response.end();
});
server.listen(8000);
console.log("Listening! (port 8000)");

Wrap Up

Node.js uses an event-driven non-blocking I/O model that makes it lightweight and efficient. It is a great system that allows us to run JavaScript in a non-browser context.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade