# Node.js Explained - A beginner guide

Node.js is a runtime environment. It was built to enable JavaScript code to run outside the web browser since JavaScript was initially built to run on web browsers.

Node.Js runs on the V8 engine which is the **fastest** followed by the Chakra engine (used by Microsoft Edge)

In this article, we will look at Node.js Key features, Use-cases, how to setup Node.js locally, as well as best practices  
I will also share links to useful resources to help you learn Node.js

## Key features of Node.js

Some of the key features of Node.js include:

1. [**Asynchronous nature**](https://www.google.com/search?q=asynchronous+meaning+in+programming) - this means it can handle multiple connections simultaneously. For instance, in situations where we have 2 events, events A and B, event B can take place without necessarily waiting for A to complete. This brings about the non-blocking I/O model
    
2. [**NPM(Node Package Manager)**](https://www.npmjs.com/) - NPM allows for easy dependency management. Node.js uses NPM. Through NPM we can get access to tons of libraries and tools for different roles such as Nodemon (a tool used to restart servers), ESLint (for code linting) and many more This also allows for **code reusability** =&gt; **efficiency** =&gt; **time-saving**  
    
    ![undefined](https://upload.wikimedia.org/wikipedia/commons/thumb/d/db/Npm-logo.svg/1920px-Npm-logo.svg.png align="left")
    
3. [**Single-Threaded**](https://www.google.com/search?q=single+threaded+meaning+in+javascript) - A task can be executed from the **beginning to the end** **without interruption**. This means only one statement can be executed at a time. Whenever there is a task, it is assigned a thread and other pending tasks will have to wait until the thread is assigned to them for execution to occur
    
    It also uses the event loop, you can read more about **event loop** [here](https://www.geeksforgeeks.org/what-is-an-event-loop-in-javascript/)
    

![Asynchronous and Single-threaded JavaScript? | The Codest](https://thecodest.co/images/uploaded/2020/03/asynchronous-and-single-threaded-javascript-meet-the-event-loop/runtime-architecture.png align="left")

**JavaScript everywhere** - This means everything in Node.js is JavaScript code This means we can use our Js for the client side and also for the backend.

## **Use Cases of Node.js**

Node.Js is used in:

1. **Web applications** - mostly to provide server-side functionalities
    
2. **API servers** - Node.js is used to create ***lightweight*** and ***efficient*** **API** servers
    
3. **Real-time applications** - it is suitable for building online games, chat apps and also collaborative tools
    
4. **IoT(Internet of Things)** - to handle data streaming, realtime analytics and device communication
    

## **Getting started**

For this you need to install Node on [Windows](https://nodejs.org/en/download), [Linux](https://nodejs.org/en/download) or [MacOs](https://nodejs.org/en/download)

[Download Node.js](https://nodejs.org/en/download)

1. Create a new folder, inside it open a terminal window and type `npm init -y`
    
2. run `npm install` command
    
3. create a file `server.js` and inside it, write the following snippet
    
    ```javascript
    const http = require('node:http');
    const hostname = '127.0.0.1'; //refers to localhost
    const port = 3000;
    const server = http.createServer((req, res) => {
      res.statusCode = 200;// set status code to 200 (success)
      res.setHeader('Content-Type', 'text/plain');
      res.end('Hello World\n');
    });
    server.listen(port, hostname, () => {
      console.log(`Server running at http://${hostname}:${port}/`);
    });
    // Server running at http://127.0.0.1:3000/
    ```
    
    1. On the terminal, type `node server.js`
        
    2. Boom, you are now running Node.js 🥳🥳🥳
        

In most cases, we use [**Express.Js**](https://expressjs.com/) inside Node.js (Fast, unopinionated, minimalist web framework for [Node.js](https://nodejs.org/en/))

## Express + Node.js guide

To get started,

1. Inside your working directory, open terminal window and run `npm init -y`
    
2. On the terminal, run `npm install express`
    
3. Oreate `app.js` and inside it paste
    
    ```javascript
    const express = require('express')
    const app = express()
    const port = 3000
    
    app.get('/', (req, res) => {
      res.send('Hello World!')
    })
    
    app.listen(port, () => {
      console.log(`Example app listening on port ${port}`)
    })
    ```
    
    1. On the terminal, run `node app.js`
        
    2. Boom, now you are running **Express.Js** inside of **Node.js**
        

## **Challenges and Best Practices:**

In most situations you are going to face some obstacles when using Node.js

1. [**Security**](https://nodejs.org/en/guides/security) - Node.js is vulnerable to (XSS) [Cross-site scripting](https://portswigger.net/web-security/cross-site-scripting) and [SQL attacks](https://www.w3schools.com/sql/sql_injection.asp). ***Best practice***: Ensure Input validation, authentication and authorization mechanisms For instance, when dealing with user passwords, you can use a npm package; [Bcrypt](https://www.npmjs.com/package/bcrypt) to handle **encryption** and **decryption** of **passwords** to and fro the database.
    
    ![8 Best Practices To Increase Security In Node.js | Blog - BairesDev](https://bairesdev.mo.cloudinary.net/blog/2023/09/Best-Practices-To-Increase-Security-In-Node.js.jpg?tx=w_3840,q_auto align="left")
    
2. [**Error handling**](https://stackify.com/node-js-error-handling/) - use [try/catch blocks](https://www.w3schools.com/java/java_try_catch.asp) and error middleware to manage errors effectively such as instances when the user enters wrong passwords, email etc.
    
3. [**Callback hell**](https://www.geeksforgeeks.org/what-is-callback-hell-in-node-js/) - deeply nested callbacks can make the code difficult to read and maintain.
    
    ***Best practice***: Use asynchronous patterns such as [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), [async/await](https://www.w3schools.com/js/js_async.asp) to write a more readable code.
    
4. [**Performance monitoring**](https://middleware.io/blog/nodejs-performance-monitoring/) - Use **profiling tools** to identify bottlenecks and optimize performance of Node.js applications.
    

## **Future trends of Node.js**

Node.js is expected to play a major role in

1. **Machine learning and AI** - Developers will be using Node.js to build server-side APIs which handle real-time data processing  
    
    ![Difference between Artificial intelligence and Machine learning - Javatpoint](https://static.javatpoint.com/tutorial/machine-learning/images/ai-vs-machine-learning.png align="center")
    
      
    
2. **Serverless computing** - Node.js is well-suited for serverless computing due to its lightweight and event-driven architecture
    
3. **Edge computing** - Node.js is likely going to be used for building apps that run on edge devices, resulting in efficiency
    

## **Case studies**

Major applications, **PayPal**, **Netflix**, **LinkedIn** are all built with **Node.js**

One thing to note is that, they rarely **slow down** or **crash.** That is the beauty of building applications with Node.js  
  

![Software Reliability](https://users.ece.cmu.edu/~koopman/des_s99/sw_reliability/Image2.gif align="left")

## **Resources to learn Node.js**

1. **Backend development and APIs with Node** - [https://www.freecodecamp.org/learn/back-end-development-and-apis/](https://www.freecodecamp.org/learn/back-end-development-and-apis/)
    
2. **Node.js Tutorial (codevolution Youtube)** - [https://www.youtube.com/playlist?list=PLC3y8-rFHvwh8shCMHFA5kWxD9PaPwxaY](https://www.freecodecamp.org/learn/back-end-development-and-apis/)
    
3. **Introduction to Node.js (Official documentation)** - [https://nodejs.org/en/learn/getting-started/introduction-to-nodejs](https://www.freecodecamp.org/learn/back-end-development-and-apis/)
    
4. **Node and Express.js Full Course (Youtube)** - [https://www.youtube.com/watch?v=Oe421EPjeBE](https://www.freecodecamp.org/learn/back-end-development-and-apis/)
    

It is important to note that while using these resources, focus on building projects rather than reading or watching passively
