📕
TIC
  • Tehnologii ale Informaţiei şi Comunicaţiilor (TIC)
  • Basic web principles
    • How web pages work
    • The pillars of a web page
    • Extra: Getting Started with GitHub
  • Basic HTML
    • Description and Basic Syntax
    • Extra resources
  • Basic CSS
    • Description and Basic Syntax
    • Advanced Positioning
    • Extra Resources
  • Basic Javascript
    • Description and basic syntax
    • The Document Object Model
    • Extra Resources
    • Basic assignment
    • The Color Game
  • Advanced Javascript
    • Runtime Engine, Callstack, Scope
    • ES6
  • Advanced Javascript 2
  • Programming paradigms
  • OOP Javascript
  • Functional Programming
  • OOP vs. Functional Programming
  • Asynchronous Javascript
  • Backend Javascript
    • NodeJS
    • ExpressJS
    • REST APIs
    • Authentication and Authorization
  • Firebase
    • NoSQL Databases
    • Database as a Service
    • Google Cloud Firestore
    • CRUD operations
    • Securing your database
  • Basic VueJS
  • Agenda: VueJS and Frontend Frameworks
  • Single Page Applications
  • VueJS basic syntax
  • Vue Components
  • Advanced VueJS
  • Advanced apps with Vue CLI
  • Vue Router
  • SPA State Management - Vuex
  • Composition API
  • Evaluation
    • Final Individual assignment
Powered by GitBook
On this page
  • What is NodeJS?
  • Installation
  • Use
  • Basic Example of starting a server
  • Popular Node.js tools and libraries
  • npm (Node Package Manager)
  • Express.js
  • Mocha
  • Chai
  • Others
  • Basic Express.js Example
  • [optional] Writing unit tests
  • Step 1: Project Setup
  • Step 2: Create the Express Application (app.js)
  • Step 3: Create the Unit Test (test.js)
  • Step 4: Update package.json for Testing
  • Step 5: Run the Tests

Was this helpful?

  1. Backend Javascript

NodeJS

What is NodeJS?

NodeJS is a JavaScript runtime environment based on the V8 engine, and it's typically used as a backend programming language. It was launched in 2009, initially for Linux, but quickly gained popularity and became available for the other OSs.

Node.js has revolutionized the way we build web applications by introducing an asynchronous, event-driven architecture and a powerful single-threaded non-blocking I/O model. This combination enables Node.js to handle multiple concurrent requests efficiently, making it ideal for real-time applications and large-scale data processing.

Event-Driven Architecture

Node.js applications are built upon an event-driven architecture, where the program waits for events to occur rather than continuously polling for data (as opposed to Apache HTTP Server, Nginx, or IIS). This approach allows Node.js to handle multiple concurrent requests without blocking the main thread, making it highly scalable and efficient.

It is a common practice to have an Nginx web server in front of a Node.js application. This is because Nginx offers several advantages over Node.js for serving static content, and it can also be used to load balance and proxy requests to Node.js servers.

Here are some of the reasons why it is common to use Nginx in front of a Node.js application:

  • Static content serving: Nginx is very efficient at serving static content, such as HTML, CSS, and JavaScript files. This is because Nginx is designed to handle a high volume of concurrent requests, and it can cache static files in memory for faster delivery. Node.js, on the other hand, is not as efficient at serving static content, so it is better to offload this task to Nginx.

  • Load balancing: Nginx can be used to load balance requests between multiple Node.js servers. This can be useful for distributing traffic and preventing any one server from becoming overloaded.

  • Proxying: Nginx can be used to proxy requests to Node.js servers. This can be useful for adding additional features to a Node.js application, such as SSL termination or HTTP basic authentication.

  • Security: Nginx can be used to add additional security to a Node.js application. For example, Nginx can be used to block malicious requests and to protect against common web vulnerabilities.

In addition to these advantages, Nginx is also a very lightweight and efficient web server. This makes it a good choice for deploying Node.js applications, especially in production environments.

Single-Threaded Non-Blocking I/O Model

Node.js utilizes a single-threaded non-blocking I/O model, meaning that the main thread handles all JavaScript execution. When performing I/O operations, such as reading or writing files, Node.js delegates these tasks to the operating system and continues executing other code. Once the I/O operation completes, an event is emitted, notifying the program that the data is available.

Built-in Modules

Node.js comes with a rich collection of built-in modules that provide essential functionalities for developing web applications. These modules include:

  • File System (FS): Provides functions for interacting with the file system, such as reading, writing, and deleting files.

  • HTTP: Provides tools for creating and handling HTTP requests and responses.

  • Net: Enables network communication, including TCP and UDP sockets.

  • Crypto: Offers cryptographic functions for secure data handling.

  • Path: Provides tools for manipulating file and directory paths.

Installation

Use

Open a Command Prompt terminal, directly from OS or through an IDE such as VScode.

Type node -v to see the current version of NodeJS installed on the system.

For running an app, browse to the app's directory (or copy the path to the app's directory) and type node app.js (assuming your app's filename is "app").

To interrupt a running app, type CTRL+C.

Basic Example of starting a server

// Load HTTP module
const http = require("http");

const hostname = "127.0.0.1";
const port = 8000;

// Create HTTP server
const server = http.createServer((req, res) => {

   // Set the response HTTP header with HTTP status and Content type
   res.writeHead(200, {'Content-Type': 'text/plain'});

   // Send the response body "Hello World"
   res.end('Hello World\n');
});

// Prints a log once the server starts listening
server.listen(port, hostname, () => {
   console.log(`Server running at http://${hostname}:${port}/`);
})

Popular Node.js tools and libraries

npm (Node Package Manager)

npm is the default package manager for Node.js (launched in 2010). It is used to install, publish, and manage Node.js packages, which are reusable pieces of code that extend the functionality of Node.js applications. npm is an essential tool for Node.js developers, as it allows them to easily find and use the latest and greatest Node.js libraries.

Express.js

Express.js is a popular web application framework for Node.js. It provides a simple and expressive API for routing, middleware, and templating, making it easy to build web applications of all sizes. Express.js is one of the most widely used Node.js frameworks, and it is a great choice for developers who are new to Node.js or who want a simple and flexible framework.

Mocha

Mocha is a JavaScript test framework that is commonly used with Node.js applications. It provides a simple and expressive API for writing unit tests, integration tests, and behavior-driven tests. Mocha is a great choice for developers who want to write comprehensive tests for their Node.js applications.

Chai

Chai is an assertion library for Node.js. It provides a variety of assertions for testing different aspects of your code, such as values, types, and exceptions. Chai is a popular choice for developers who use Mocha, as it provides a clean and expressive API for writing assertions.

Others

In addition to these essential tools, there are many other popular Node.js libraries and frameworks, such as:

  • Socket.io: Real-time communication library

  • Passport.js: Authentication middleware

  • Babel: JavaScript compiler

  • Webpack: Module bundler

  • PM2: Process management tool

Basic Express.js Example

To install Express.js, simply run the following command (Node.js must be already installed) in the terminal with the path of your application:

npm install express --save

The --save or --s ensures that the npm library, along with its version and meta-information is added to the package-lock.json

const express = require('express');
const app = express();
const port = 3000;

const logger = require('morgan'); //importing a HTTP logger

app.use(logger('dev')); //using the HTTP logger library

app.get('/', (req, res) => {
  res.setHeader('content-type', 'text/plain');
  res.status(200);
  res.send('Hello World!')
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}!`)
});

Running the app:

[optional] Writing unit tests

Creating a simple Express application with a single endpoint that returns the sum of two query parameters, and then writing a unit test for this endpoint using Mocha, involves several steps. Here's a breakdown of how you can do this:

Step 1: Project Setup

Initialize a new Node.js project:

mkdir sum-app
cd sum-app
npm init -y

Install Express and Mocha (along with chai for assertions):

npm install express
npm install mocha chai --save-dev

Create the files:

  • app.js for the Express application.

  • test.js for the Mocha tests.

Step 2: Create the Express Application (app.js)

const express = require('express');
const app = express();

const port = process.env.PORT || 3000;

app.get('/sum', (req, res) => {
    const a = parseInt(req.query.a, 10);
    const b = parseInt(req.query.b, 10);

    if (!isNaN(a) && !isNaN(b)) {
        res.send({ sum: a + b });
    } else {
        res.status(400).send({ error: 'Invalid input' });
    }
});

app.listen(port, function() {
    console.log(`Server listening on port ${port}`);
  });

module.exports = app;

Step 3: Create the Unit Test (test.js)

const chai = require('chai');
const chaiHttp = require('chai-http');
const app = require('./app');

chai.use(chaiHttp);
const { expect } = chai;

describe('GET /sum', () => {
    it('should return the sum of two query parameters', (done) => {
        chai.request(app)
            .get('/sum')
            .query({ a: '5', b: '3' })
            .end((err, res) => {
                expect(res).to.have.status(200);
                expect(res.body).to.deep.equal({ sum: 8 });
                done();
            });
    });

    it('should return an error for invalid input', (done) => {
        chai.request(app)
            .get('/sum')
            .query({ a: 'x', b: '3' })
            .end((err, res) => {
                expect(res).to.have.status(400);
                expect(res.body).to.deep.equal({ error: 'Invalid input' });
                done();
            });
    });
});

Step 4: Update package.json for Testing

Modify the test script in your package.json to run Mocha:

"scripts": {
    "test": "mocha"
}

Step 5: Run the Tests

npm test

This will run your Mocha tests, which will test the /sum endpoint with valid and invalid inputs.

If successful, you should receive the following output:

PreviousAsynchronous JavascriptNextExpressJS

Last updated 7 months ago

Was this helpful?

Go to download the installation file and follow the instructions.

You can check the response through your browser at the following URL:

https://nodejs.org/en/
https://www.npmjs.com/
http://localhost:3000/
Node.JS installation page welcome screen