My Logo

PUBLISHED JANUARY 02, 2024

Teghen Donald Ticha
Lastly Updated: 3 months ago
Reading time 14 mins

Introduction to NodeJS

In this series part, I introduce nodeJS and some technical concepts associated with it. I also show how easy it is to setup and start a simple nodeJS web server.
Introduction to NodeJS

Prerequisite

No prior knowledge is required for this part, although some familiarity with at least one other server-side development stack is a plus.

But not to worry, this part assumes zero prior knowledge of server-side development.

According to the nodeJS docs, It is an open-source and cross-platform JavaScript runtime environment 🤔.

To understand this, let’s see what a javaScript runtime environment is.

Basically, it refers to the environment in which JavaScript code is executed, meaning that it includes everything needed to run a JavaScript program, such as the JavaScript engine, libraries, and other components that facilitate the execution of JavaScript code.

So in mathematical terms, nodeJS = JS runtime + node specific APIs(to be discuss later on).



NodeJS runs the V8 JavaScript engine, the core of Google Chrome, outside of the browser. This allows nodeJS to be very performant.

In other words, NodeJS brings the capabilities of JavaScript, traditionally associated with the client-side (browser), to the server-side, enabling developers to use a single programming language (JavaScript) for both front-end and back-end development.

The V8 engine (read more at https://v8.dev/ ), which is optimized for high-performance execution, plays a crucial role in making nodeJS efficient and powerful for server-side applications.

Node Event Loop Cycle


A node app is single threaded but non-blocking, meaning that it runs multiple concurrent processes, without creating a new thread for every process. So you may ask how is that possible?

Well, the answer is simple. NodeJs ships in with a set of asynchronous I/O primitives in its standard library that prevent JavaScript code from blocking, in fact, libraries in nodeJS are written using non-blocking paradigms by default, making blocking behavior the exception rather than the norm.

In other words, nodeJS is asynchronous by default. It’s up to the developer to opt for synchronous behavior.

Single-threaded vs Multithreaded Processes

Single thread processes execute all instructions in a single sequence. In other words, only one command is processed at a time.

The opposite of single-threaded processes are multithreaded processes. These processes allow the execution of multiple parts of a program at the same time.

Single Vs Multi Threading



Node js is single-threaded, but there are some libraries in Node js that are not single-threaded.

NodeJS uses its libuv library to handle tasks related to the operating system, such as asynchronous I/O-based tasks of operating systems, networks, concurrency, etc...

When Node requests simultaneous process execution, the Libuv library configures a set of threads to perform the operations, using the power of all CPU cores.

Since modern machines have multiple cores, each thread in the pool is assigned to each core.

This results in one thread per core. With this configuration, all threads will run their process on each core in parallel.

NodeJS Thread Pool


In nodeJS, I/O operations like networking, accessing a database or reading from the filesystem, are all asynchronous, so the thread isn't blocked and CPU cycles aren’t wasted.

Instead, nodeJS simply runs them on the side, and only resumes the operations when they complete or fail.

This allows nodeJS to handle thousands of concurrent connections with a single server without introducing the burden of managing thread concurrency, which could be a significant source of bugs.

Lets setup a simple nodeJS web server that response with a hello-world message.

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Save the snippet above in a server.js file and in your terminal, run `node server.js`
NB: We will discuss nodeJS installation is discussed in the


Lets break it down:

First, we include the http module

Node.js has a fantastic standard library , including first-class support for I/O processes included networking.

The `createServer()` method of the http module, creates a new HTTP server and returns it.

The server is set to listen on the specified port and host name(which are declared as constants). When the server is ready, the callback function is called, in this case informing us that the server is running.


As discussed above, listen operation is asynchronous, so the node handles that as a subprocess and only returns to it when it is ready or throws an error.

When a new request is received, the request event  is called, providing two objects:

  1. 1.a request (an http.IncomingMessage object) which provide details about the request. We didn’t use that in our example.
  2. 2.a response (an http.ServerResponse object) used to return data to the caller.


In our case:

res.statusCode = 200;

we set the statusCode property to 200, to indicate a successful response. (read more 👉 http codes)


We set the Content-Type header:

res.setHeader('Content-Type', 'text/plain');


We end the response and append a message to the body

res.end('Hello World\n');


In this series part, we covered some definitions and terminologies associated with nodeJS. We also saw how simple it is to setup a web server and start receiving and responding to http requests.

In the next part, we will focus on installing and setting up nodeJS.

All Chapter Parts for NodeJs In Theory, An absolute Beginner’s Overview
  1. Chapter 1 , Part 1 : Introduction to NodeJS

    In this series part, I introduce nodeJS and some technical concepts associated with it. I also show how easy it is to setup and start a simple nodeJS web server.

  2. Chapter 1 , Part 2 : How to Install and Setup NodeJS

    In this series part, I run you through the various ways to install nodeJS. I also discuss how to install nvm and use it to switch between different node versions.

  3. Chapter 1 , Part 3 : How much JavaScript do you need to learn NodeJS

    In this series part, we explore the nuanced relationship between JavaScript and NodeJS, highlighting some subtle distinctions between the two environments.

  4. Chapter 1 , Part 4 : The v8 Engine and the difference Between NodeJS and the browser

    In this series part, we explore the V8 engine and how it interacts with nodeJS. We also discuss node’s event loop and uncover the mystery behinds node’s ability to handle concurrent operations.

  5. Chapter 1 , Part 5 : NPM, the NodeJS package manager

    Discover the essentials of npm, the powerful package manager for Node.js. Learn installation, management, publishing, and best practices

  6. Chapter 1 , Part 6 : NodeJS in Development Vs Production

    Explore how Node.js behaves differently in development and production environments. Learn key considerations for deploying Node.js applications effectively.

  7. Chapter 2 , Part 1 : Asynchronous Flow Control

    In this series part, we'll explore various aspects of asynchronous flow control in Node.js, from basic concepts to advanced techniques.

  8. Chapter 2 , Part 2 : Blocking vs Non-blocking I/O

    Explore the differences between blocking and non-blocking I/O in Node.js, and learn how to optimize performance and scalability.

  9. Chapter 2 , Part 3 : Understanding NodeJS Event loop

    Exploring the Node.js event loop by understanding its phases, kernel integration, and processes enabling seamless handling of asynchronous operations in your applications.

  10. Chapter 2 , Part 4 : The NodeJS EventEmitter

    Explore the power of Node.js EventEmitter: an essential tool for building scalable and event-driven applications. Learn how to utilize it effectively!

  11. Chapter 3 , Part 1 : Working with files in NodeJS

    Gain comprehensive insights into file management in Node.js, covering file stats, paths, and descriptors, to streamline and enhance file operations in your applications.

  12. Chapter 3 , Part 2 : Reading and Writing Files in NodeJS

    Uncover the fundamentals of reading and writing files in nodeJS with comprehensive examples and use cases for some widely used methods.

  13. Chapter 3 , Part 3 : Working with Folders in NodeJS

    Unlock the secrets of folder manipulation in Node.js! Explore essential techniques and methods for working with directories efficiently

  14. Chapter 4 , Part 1 : Running NodeJS Scripts

    Master the command line interface for executing nodeJS scripts efficiently. Learn common options and best practices for seamless script execution

  15. Chapter 4 , Part 2 : Reading Environment Variables in NodeJS

    Learn how to efficiently manage environment variables in nodeJS applications. Explore various methods and best practices for security and portability

  16. Chapter 4 , Part 3 : Writing Outputs to the Command Line in NodeJS

    Learn essential techniques for writing outputs in nodeJS CLI. From basic logging to formatting and understanding stdout/stderr.

  17. Chapter 4 , Part 4 : Reading Inputs from the Command Line in NodeJS

    Learn the various ways and strategies to efficiently read command line inputs in nodeJS, making your program more interactive and flexible.

  18. Chapter 4 , Part 5 : The NodeJS Read, Evaluate, Print, and Loop (REPL)

    Explore the power of nodeJS's Read, Evaluate, Print, and Loop (REPL). Learn how to use this interactive environment for rapid prototyping, debugging, and experimentation.

  19. Chapter 5 , Part 1 : Introduction to Testing in NodeJS

    Discover the fundamentals of testing in nodeJS! Learn about testing types, frameworks, and best practices for building reliable applications.

  20. Chapter 5 , Part 2 : Debugging Tools and Techniques in NodeJS

    Explore essential debugging tools and techniques in Node.js development. From built-in options to advanced strategies, and best practices for effective debugging.

  21. Chapter 6 , Part 1 : Project Planning and Setup

    Discuss the planning and design process for building our interactive file explorer in Node.js, focusing on core features, UI/UX design, and implementation approach and initial setup.

  22. Chapter 6 , Part 2 : Implementing Basic functionalities

    In this guide, we'll implement the basic functionalities of our app which will cover initial welcome and action prompts.

  23. Chapter 6 , Part 3 : Implementating Core Features and Conclusion

    In this guide, we'll complete the rest of the more advanced functionalities of our app including, create, search, sort, delete, rename and navigate file directories.