Node.js and Node Package Manager

Written by Full-Stack Developer

May 8, 2024
Node.js and Node Package Manager

In developing websites, software, and applications the use of libraries and frameworks has contributed to enhancing efficiency and productivity in fast-paced environments. Web developers can access a variety of libraries and frameworks that are effectively organized by a platform designed to simplify their utilization.

These libraries have made it easier for web developers to perform less crucial tasks faster and more efficiently. Many functions in web development have packages or rely on external modules, an example would be “react-scroll" which enables smooth scrolling within a single-page application.

This platform/software is called Node.js, and it’s very popular in the JavaScript community. So, what is Node.js, and why is it important?

In this article, we’ll be breaking down what Node.js and node package manager entail and their usefulness to JavaScript developers,

let’s dive in!

Node / Node.js?


Node not to be confused with Node.js is a prevalent term in computer science. A node can be a document, images, or videos, it could also be a computer or device within a network. This means that a node or nodes varies depending on various concepts.

In JavaScript DOM (Document Object Model), for instance, the DOM tree consists of tree objects called nodes, these nodes refer to entities within the structure of an XML or HTML document. An example is the “element node” which represents elements in the document e.g. <p> </p>

In the context of web development, Node, or Node.js as it is commonly referred to serves as a cross-platform JavaScript runtime environment. This means it can operate on multiple environments within Windows, Linux, UNIX, and macOS).

As a runtime environment, Node.js allows the execution of programs or applications that are outside of a web browser. Noteworthy key points include:

  • It’s mostly used to build backend applications
  • It’s not a programming language
  • It can run on multiple environments

Initially, JavaScript was developed as a client-side language to be used in web browsers and to increase website functionality. It could only be executed inside the browser environment which made it quite limited.

So, in 2009 Ryan Dahl thought it would be great for JavaScript to be able to execute outside a browser after encountering limitations with server-side programming languages.

The goal became redefining how we think about I/O operations. Now, JavaScript has evolved, spreading out such that we can now run JavaScript as a server, on desktops, on mobile applications, etc.

When we write code, the browser has to convert the code to machine code which is the language the computer understands.

This machine code is in binary numbers 0’s and 1’s - and is what the computer processor understands. The conversion to machine code is performed by an engine. There are several JavaScript engines, examples include; SpiderMonkey by the Mozilla Foundation, chakra by Microsoft, and V8 engine by the Chromium project

Node.js uses Google's V8 engine as its runtime environment for executing code on the server side. Ryan Dahl incorporated the V8 engine into a C++ program this means that NodeJS contains a JavaScript engine that can execute JavaScript Code. V8 is the most famous among all these engines because it converts JavaScript code directly into machine code. As well, it is used to develop applications that run JavaScript on the client-side and server-side.

Use Cases

  • IoT systems,
  • APIs
  • Complex Single-Page Application.
  • Micro Services Applications
  • Streaming Applications

There are three important components of Node.js, and they are

1. JavaScript Runtime: The JavaScript runtime is the environment where JavaScript code is executed. Node.js is a runtime environment built on the V8 engine, which is responsible for executing JavaScript code outside of web browsers (e.g., Chrome) and in server-side environments (e.g., Node.js).

2. Event Loop: Libuv handles file system access, networking asynchronous operations, and the concurrency model. Libuv manages the event loop in NodeJS, which dictates how Node.js performs asynchronous operations. The event loop allows non-blocking I/O operations asynchronously. Its task is to check the queue for pending events and execute them iteratively.

3. Standard Library: The Node.js standard library consists of modules and APIs for different tasks, such as network communication, HTTP handling, file system operations, etc. It also comprises various utility functions.

90%

💸 90% OFF YOUR FIRST MONTH WITH ALL VERPEX SHARED WEB HOSTING PLANS

with the discount code

MOVEME

Save Now

Benefits of Node.js


1. Speed: It is single-threaded and based on even driven non-blocking I/O (Input-Output) model making it lightweight and efficient. Let's look at these terms down one at a time;

  • Single Threaded: This means Node.js uses one thread of execution to execute JavaScript code.

  • Event Driven: Node.js listens for events e.g. requests from users and responds as they occur.

  • Non-Blocking I/O: Node.js is single-threaded, however, it uses non-blocking I/O techniques by performing input and output operations without waiting for the operations to finish before moving to the next task. When the operation is finished a callback is prompted to handle the result.

2. Easy to Learn: It is built on JavaScript therefore learning to work with it as a JavaScript developer on the server side is easier.

3. Node Package Manager: The Node Package Manager (NPM) is a package manager for Node.js that extends the ecosystem of packages, changing the way code can be shared and distributed within the Node.js community.

Also, NPM makes it easier for developers to install, and manage JavaScript packages, frameworks, and libraries.

4. Open-Source: Its source code is available for modification and distribution. It is transparent for users or developers who would like to identify and address vulnerabilities or customize and extend Node.js

Node Package Manager:


NPM can be referred to as a repository (think of this term as a storehouse) that contains tools developers or software engineers use to develop websites, web applications, IOT systems, etc.

Node Package Manager is the standard package manager for Node.JS with over 2.1 million packages listed on the NPM registry, making it the world's largest single code repository.

Using the Node Package Manager, you can download packages like Angular, React, and Vue. Module or packages can be installed, or uninstalled from a command-line interface or a terminal.

Also, node package manager users can manage versions or dependencies for programs to run smoothly as versions of these packages are regularly upgraded.

NPM package.json


NPM projects generally contain a file called a package.json which can be initialized by typing the following command npm init (npm initialization) - This command sets up a new or existing npm package. The package.json file contains project details, scripts, metadata, and dependencies.

A package.json package looks like the example below, here we have different properties which we’ll break down into bits.

{
  "name": "node-project",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "main": "app.jsx",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "lint": "eslint . --ext js,jsx --report-unused-disable-   directives --max-warnings 0",
    "preview": "vite preview"
  },
  "dependencies": {
    "prop-types": "^15.8.1",
    "react": "^18.2.0",
    "react-datepicker": "^6.1.0",
    "react-dom": "^18.2.0",
    "react-lazy-load-image-component": "^1.6.0",
    "react-scroll": "^1.9.0",
    "react-toastify": "^10.0.4",
    "eslint-plugin-import-path": "^0.0.2",
    "react-multi-carousel": "^2.8.4"
  },
  "devDependencies": {
    "@types/react": "^18.2.55",
    "@types/react-dom": "^18.2.19",
    "@vitejs/plugin-react": "^4.2.1",
    "autoprefixer": "^10.4.17",
    "eslint": "^8.56.0",
    "eslint-config-airbnb": "^19.0.4",
    "eslint-config-prettier": "^9.1.0",
    "eslint-plugin-import": "^2.29.1",
    "eslint-plugin-react": "^7.33.2",
    "eslint-plugin-react-hooks": "^4.6.0",
    "eslint-plugin-react-refresh": "^0.4.5",
    "postcss": "^8.4.35",
    "tailwindcss": "^3.4.1",
    "vite": "^5.1.0"
  }
}

Name: Where the name of the project or package resides

Private: In this case, the package is for private use, and it’s not to be published or distributed that’s why private is set to true (“private”: true)

Version: current version of npm

Type: “type”: module indicates the use of ECMAScript Modules in a NodeJS project.

Main: Entry part of the project

Scripts: custom scripts used to execute npm

Dependencies: contains libraries or utilities to ensure the application works as intended

DevDependencies: include tools and libraries necessary during development but not in production.

Build a Basic Web Server with Node.js


Before we proceed to build a web server with NodeJS, download and install the latest version of node.js on your computer. Visit this official Node.JS website https://nodejs.org/en, and follow the instructions on downloading.

Downloading NodeJS

If you notice, there are two versions of node.js; LTS and Current. The LTS version is recommended for users because of its long-term community support, is dependable, requires few updates, and receives regular security updates amongst other features.

The latest version may contain features that may need improvements because new features that haven't been used in real-world projects may introduce bugs, compatibility issues, etc. This version is mainly for library authors.

Let's proceed to build a web server with Node.JS


When we visit a site like Google on the internet and search for a website like Verpex, we act as the client (clients are interconnected devices e.g. mobile phones, web accessing software) by making the request, while Google, responds with the details of our request, represents the server (servers are computers that store web pages, sites or apps). This process is known as the client-server model

For any request or response to occur, HTTP (Hypertext Transfer Protocol) is at work, this is the basis of communicating over the web. HTTP defines a format for clients and servers to speak to each other.

This defines the format of the data being transferred between the client and server ensuring smooth comprehension. It allows the server to understand the client's request and ensure that the client understands the server's response.

“The client sends an HTTP request and the server responds with an HTTP response.”

We can create a web server using Node.JS because it leverages operating systems functionality such as networking. As well as an event loop to run tasks asynchronously which is perfect for creating web servers that can simultaneously handle large amounts of requests.

The Node server follows an HTTP format using an HTTP module that allows the creation of web servers that can transfer data over HTTP.

Step One: Check Node Version

To verify that Node.js is installed correctly, verify the installation by typing 'node -v' in your terminal. This command will display the latest version of Node.js installed

verify the node.js installation

Step Two:

Open your IDE (in this example, we’ll be working in VSCODE) and create an index.js file.

create an index.js file

Step Three:

Import the HTTP module and import the create server method on the module. This method accepts a call-back function as an argument.

Import the HTTP module

Step Four:

The create server method accepts a callback function as an argument - the function receives a request and response (

‘req’ - Represents the HTTP request sent by the client to the server. ‘res’ - Represents the HTTP response sent by the server to the client.

Node.JS event module

HTTP extends the event emitter class, which is provided by Node.JS ‘event’ module allowing events. It triggers functions or listeners to be called when an event occurs.

The function req specified is a request listener this means that when the request gets to the server the callback function req is executed - this argument contains information about the request coming in.

The response argument is used to generate the response that has to be sent to the client. Node handles the incoming request while we would have to write code that is to be sent back as a response.

Step Five: Invoke writeHead method on the response object, and add the HTTP status code argument.

Invoke writeHead method

Step Six: Invoke the end method in response and pass a string - this means we’ve created a response to the incoming request.

Invoke the end method

Step Seven: Specify the content type of response

Specify the content type of response

Step Eight: The server is informed to listen for incoming requests. For this to happen, the create server method is stored in a constant.

create server method

In the server constant, we’ll invoke the listen method and pass in the 3000 port number which is the default or conventional port for development. Note we also included a callback function so we can see when it runs in our console.

Step Nine: Run the node index in your terminal

Run the node index

Step Ten: Make a request on port 3000 by going to the browser, type localhost:3000 click the enter key and the response that was created would be displayed on the screen.

Make a request on port 3000
20%

💰 EXTRA 20% OFF ALL VERPEX SHARED WEB HOSTING PLANS

with the discount code

AWESOME

Save Now

Summary


Node.js is a powerful tool that has positively altered the development of applications and websites. By leveraging JavaScript on the server side, developers can build scalable applications.

This technology continues to evolve, with its extensive npm ecosystem containing a large collection of libraries and frameworks, allowing for the rapid development of robust and efficient websites and applications.

Frequently Asked Questions

Which is faster NodeJS or Golang?

Golang is considered to be faster than Node.js, particularly for CPU-bound tasks or applications that require high concurrency and low latency.

How does Verpex ensure the security of Node.js applications hosted on their platform?

Verpex employs a multi-layered security approach for Node.js applications, including regular security updates, firewall configurations, intrusion detection systems, and security enhancements tailored to Node.js. We also offer SSL certificates for encrypted data transmission.

Does Verpex offer integrated development tools for Node.js, such as IDE support or Git repositories?

Verpex provides integration with popular development tools, including IDEs and Git repositories, to streamline the development process for Node.js developers.

What kind of server-side optimizations are implemented to enhance the performance of Node.js applications?

Verpex employs server-side optimizations such as load balancing, server caching, and resource scaling to ensure optimal performance for Node.js applications. These optimizations are fine-tuned to the specific needs of your application.

Jivo Live Chat