Evolution of a Node.Js API, Zoe.Js — Node.Js

Adams Academy
The Startup
Published in
6 min readJul 17, 2020

Node.js is a Runtime Environment for executing JavaScript code. It is not a language and it is not a framework, it's more of a platform.

In the browser (client) Chrome uses its V8 engine to run Javascript. Node.js is built on Chrome's V8 Javascript engine and runs JavaScript on the server.

Node.js operates on a single-thread event-loop, using non-blocking I/O call, allowing it to support tens of thousands of concurrent connections — wikipedia.org

Sounds good, but what are these? Let’s take a look…

Non-blocking I/O calls

This means Asynchronous Input/Output.

I/O refers to an interaction with the file system or the network. For example reading from a file, writing to a database or performing a web request.

A program which has an Asynchronous (async) statement, doesn't have to wait for the statement to be completed, it continues the processing with the next code line. When the async task is finished, the program calls the registered callback.

So an async statement does not block the main program, it is non-blocking.

Single threaded

From a developer perspective Node.js looks like single-threaded, although under the hood libuv handles threading and the Event loop.

In fact there is a pre-allocated set of threads called Thread Pool, which handles parallel tasks such as file system reading/writing, database operations or web requests. In reality Thread Pool is not only operates where Node.js executes async tasks, libuv prefers to run async task on OS level.

If the Main Thread gets a task, it pulls a thread from the Thread Pool and that thread executes the task. When that thread is finished, it informs the Main thread and it add the registered callback to theEvent queue.

Event loop

geeksforgeeks.org

While your program is running, Node.js collects the I/O events and when one of them is completed, it pushes the event and its handler (callback) to the Event queue.

With the Event queue Node.js is tracking the unfinished async operations. Event loop is basically an endless loop which goes through the queue and invokes the handler for a given event.

Why use Node.js?

Node.js is a fast, efficient and highly scalable platform thanks to its event driven, non-blocking I/O.

In contrast to PHP, Node.js doesn’t have to sit and wait until a database reading operation completes, it can process another async event or another request in the meantime.

And you can also use the same language on your front- and backend as well. Any team member is able to understand the code on both sides.

What is Node.js used for?

With Node.js you can build any kind of application, although you shouldn’t write CPU intensive programs, because CPU intensive statements block your program, therefore you lose one of the best adventage of Node.js, non-blocking I/O.

The recommended areas of usage are:

  • REST APIs
  • Microservices
  • Real time applications
  • CRUD apps
  • Tools
  • Testing

Installation of Node.js

In order to install Node.js on you computer, visit https://nodejs.org/en/download

Package Manager

The default package manager for Node.js is npm, it stands for Node Package Manager. It is a package repository and a command-line utility. npm can maintain your package dependencies, install packages or run scripts. A package can be an entire framework, a library, a tool and so on.

package.json is the file which describes the project with its dependencies. You can easily create a standard package.json with the npm init -y console command:

npm init -y

For installing a package locally to your project (packages installed in the node_modules folder), simply type:

npm install express

Or you can install a package globally to your system with:

npm install -g nodemon

Modules

Modules are for breaking down large programs into smaller, organizable and managable files. They provide reusability of code.

A module can be:

  • a core Node.js module (os, path, fs, http, etc.)
  • 3rd party module/package installed with npm
  • own module (file)

Every file in a Node.js application is considered of a module. Variables and functions defined in a module file are scoped to that module.

Module wrapper

Before a module’s code is executed, Node.js will wrap it with a function wrapper that looks like the following:

This makes variables to module scoped, not global scoped and the parameters ( exports, require, etc.) look like module specific.

Module systems

Module system are for organizing your code, hiding implementation details, exposing the public interface ( exports) and reusing modules ( require, import). Javascript didn't have a module system before ES6, so Node.js is created its own one.

Node.js Module system

Node.js uses its own Module system which is derived from the CommonJS Module format specification. Modules are loaded synchronously, therefore processed in the order they occur and Modules are cached after the first time they are loaded.

Modules load in the following order:

  • Built-in Node.js core modules such as os, path, fs
  • NPM modules from the node_modules folder
  • Local modules where the path starts with ./, ../, or /

Multiple Exports and Require

In a module you can export multiple functions and variables. Importing a module happens with the require keyword.

require first looking after the required module inside node_modules directory

Default Module Exports and Require

In a module you can also export a default member such as a class or an object. In this case require returns with the Order class.

ECMAScript Modules (ESM)

From Node.js version 12 Experimental support for ECMAScript Modules is enabled by default. Modules are loaded asynchronously (by default) and cached as well.

In order to use ESM in your project, add "type": "module" to your package.json file

Multiple Exports and Import

For exporting multiple functions and variables with ESM system use the export keyword.

For importing these you have basically 2 options, importing all the exported members with aliasing.

Or importing some of the members with named imports.

Default Export and Import

In order to export a default member of a module you have to use the export default keywords. Importing feels more natural than importing with Node.js Module system.

Sequence of imports

require behaves synchronously, while import works asynchronously, by default. require statements processed in the sequence they occur, now let's see what happens with import statements.

main.js imports module_1.js which imports module_2.js

And the output is:

module_2.js
module_1.js
main.js

When you execute a module containing an import declaration, the modules it imports are loaded first, then each module body is executed.

Usage of a core module

Node.js has a bunch of handy core modules such as os, url, path. This is how you handle URLs using the url core module.

The simplest web server

In order to write one of the simplest web server use the http Node.js core module. It’s so simple that you need to check the URL manually, to decide where to go next.

That’s it, run your application with node server.js and you can access your web server on http://localhost:9000

Article Series

This article (Chapter 2) is part of the Zoe.js article series. Below you can find the Next chapter and all the available Chapters.

--

--

Adams Academy
The Startup

Adams Academy helps you to cut through the noise and understand programming languages, web development with simple programming tutorials.