Full Trust European Hosting

BLOG about Full Trust Hosting and Its Technology - Dedicated to European Windows Hosting Customer

Node.js Hosting - HostForLIFE :: Using Express to Create a Node.js API with Swagger Support

clock January 2, 2024 06:50 by author Peter

Overview of Swagger in Node.js
An effective tool for planning, creating, and documenting APIs is Swagger. It gives developers a consistent vocabulary to define RESTful APIs, which facilitates their comprehension, consumption, and interaction with API endpoints. Swagger can be very helpful when producing documentation for Node.js applications that is both machine- and human-readable.

Essential Elements of Swagger
Swagger Specification/OpenAPI: A standard for characterizing RESTful APIs, the Swagger Specification is now the OpenAPI Specification. It establishes a format for machine-readable documentation of the architecture and operation of APIs.

The specification describes parameters, authentication techniques, request/response formats, API endpoints, and more in JSON or YAML.

A user-friendly interface for visualizing and interacting with the Swagger/OpenAPI documentation is called Swagger UI. It enables developers to test endpoints, investigate the API, and comprehend the typical formats for requests and responses.

The Swagger Specification is used to automatically construct the User Interface (UI), which offers an interactive method of interacting with the API.

Swagger Codegen: Based on the Swagger Specification, this tool creates client libraries, server stubs, and API documentation. This can be especially useful for preserving consistency between an API's client and server components.

Integrating Swagger in a Node.js API

To integrate Swagger into a Node.js API, you can follow these step-by-step:
Step 1. Install Necessary Packages

Use npm to install the two required packages, such as express, swagger-jsdoc, and swagger-ui-express.

1. Swagger-jsdoc

npm install swagger-jsdoc --save

2. Swagger-ui-express
npm install swagger-ui-express --save

Go to the project folder and open the terminal to install the required packages.

You can verify whether the package.json package was added or not after installation.

Step 2. Create Swagger Configuration
Write a Swagger configuration file that describes the API using JSDoc comments in the code. This configuration includes information such as API title, version, paths, parameters, and responses.

index.js

const options = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: 'Student Management System',
      version: '1.0.0',
      description: 'Student Management System covered Create, Read, Update, and Delete operations using a Node.js API',
    },
    servers:[
      {url:'http://localhost:5000/api'}, //you can change you server url
    ],
  },

  apis: ['./routes/*.js'], //you can change you swagger path
};

Step 3: Use Swagger Middleware Integration
For your Express.js application, you can use middleware packages such as swagger-jsdoc and swagger-ui-express to integrate Swagger. This middleware serves the Swagger UI and dynamically creates the Swagger Specification.

index.js
1. Import the middleware packages that are needed.

const swaggerUi = require('swagger-ui-express');
const swaggerJsdoc = require('swagger-jsdoc');

JavaScript

2 . Initialize Swagger-jsdoc.

const specs = swaggerJsdoc(options);

JavaScript

3. Serve Swagger documentation using Swagger UI.

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs));

JavaScript
Step 4. Define API Routes

Define the API routes using Express.js as usual. Swagger will automatically pick up the route information from the code comments.

Add the Swagger in studentRoute.js

1. API route : router.get("/student", getAllStudents);
Get all students
/**
 * @swagger
 * /student:
 *   get:
 *     summary: Get a list of all students
 *     tags: [Students]
 *     responses:
 *       200:
 *         description: Successful response
 *         content:
 *           application/json:
 *             example:
 *               data: [{}]
 *       400:
 *         description: Bad Request
 *         content:
 *          application/json:
 *            example:
 *             error:
 *              message: "Bad Request"
 */
//Get All Students
router.get("/student", getAllStudents);


2. API route: router.get("/student/:id", getStudent);

Get the Student by ID
/**
 * @swagger
 * /student/{id}:
 *   get:
 *     summary: Get a student by ID
 *     tags: [Students]
 *     parameters:
 *       - name: id
 *         in: path
 *         required: true
 *         description: The ID of the student
 *         schema:
 *           type: string
 *         example:
 *             658918e852a0131af4c0aab1
 *     responses:
 *       200:
 *         description: Successful response
 *         content:
 *           application/json:
 *             example:
 *               data: [{}]
 *       404:
 *         description: Student not found
 */


//Get the Student
router.get("/student/:id", getStudent);


3. API route: router.post("/student", createStudent);
Create a new student
/**
 * @swagger
 * /student:
 *   post:
 *     summary: Create a new student
 *     tags: [Students]
 *     requestBody:
 *       description: Student object to be added
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               name:
 *                 type: string
 *               address:
 *                 type: string
 *               dateOfBirth:
 *                 type: date
 *               gender:
 *                 type: string
 *               phoneNum:
 *                 type: integer
 *             example:
 *                name: "John Doe"
 *                address: "Colombo - Srilanka "
 *                dateOfBirth: 07/14/1990
 *                gender: "male"
 *                phoneNum: 01145252525
 *     responses:
 *       201:
 *         description: Successful response
 *         content:
 *           application/json:
 *             example:
 *               data: [{}]
 *       400:
 *         description: Invalid request
 */


//Create Student
router.post("/student", createStudent);


4. API route: router.put("/student/:id", updateStudent);
Update a student by ID

/**
 * @swagger
 * /student/{id}:
 *   put:
 *     summary: Update a student by ID
 *     description: Update the details of a student by providing the student ID.
 *     tags: [Students]
 *     parameters:
 *       - in: path
 *         name: id
 *         description: The ID of the student to be updated.
 *         required: true
 *         schema:
 *           type: string
 *     requestBody:
 *       description: Updated student information
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               name:
 *                 type: string
 *               address:
 *                 type: string
 *               dateOfBirth:
 *                 type: string
 *                 format: date
 *               gender:
 *                 type: string
 *               phoneNum:
 *                 type: integer
 *     responses:
 *       200:
 *         description: Successful update
 *         content:
 *           application/json:
 *             example:
 *               message: 'Student updated successfully'
 *       404:
 *         description: Student not found
 *         content:
 *           application/json:
 *             example:
 *               message: 'Student not found'
 */


//put the Student
router.put("/student/:id", updateStudent);


5. API route: router.delete("/student/:id", deleteStudent);
Delete a student by ID
/**
 * @swagger
 * /student/{id}:
 *   delete:
 *     summary: Delete a student by ID
 *     tags: [Students]
 *     parameters:
 *       - name: id
 *         in: path
 *         required: true
 *         description: The ID of the student
 *         schema:
 *           type: integer
 *         example:
 *             658918e852a0131af4c0aab1
 *     responses:
 *       204:
 *         description: Student deleted successfully
 *       404:
 *         description: Student not found
 */
//Delete the Student
router.delete("/student/:id", deleteStudent);


Step 5. Run The Application
Start the Node.js application, npm start
Access the Swagger documentation by visiting the specified endpoint, usually /api-docs or a custom path. Example:  http://localhost:5000/api-docs/

Following these steps, you can enhance your Node.js API with interactive and well-documented Swagger/OpenAPI documentation, making it easier for developers to understand, test, and integrate with your API.

1. Go to the swagger path  http://localhost:5000/api-docs/

2. Click on the Try it out button.

3. Click on the Execute button, and get the response.

4. Get the Response.

 

The tutorial walks readers through the process of using Express to create a Node.js API that supports Swagger. To include Swagger into a Node.js API, install the required libraries, make a Swagger configuration file, then use Express.js to define the API routes.

With an emphasis on using Swagger annotations in JSDoc comments to automatically generate interactive Swagger documentation, the book offers thorough code examples for every step. The last section explains how to launch the application and use Swagger UI to view the documentation, which enables developers to easily comprehend, test, and work with the API. The procedures are illustrated clearly in the accompanying photos, which also show how to use the Swagger UI and submit API queries.



Node.js Hosting - HostForLIFE :: How Do I Fix Nodemon Command Is Not Recognized In Node.js Terminal?

clock November 9, 2023 07:53 by author Peter

We will look at two key features of working with Node.js and Nodemon in this article. First, we'll walk you through the process of installing Nodemon, a critical tool for developers aiming to speed up the development of Node.js apps. By understanding how to install Nodemon, you can use its power to automatically restart your server anytime code changes. You will save time and effort as a result of this.


The "Nodemon command is not recognized" terminal error is a common and vexing issue for developers. We'll investigate the core causes of this problem and provide you with a clear, step-by-step plan for resolving it. Whether you're a seasoned Node.js developer or just getting started, mastering these core skills will result in a more efficient and successful development process.

node -v

Step 2. Open Your Terminal
To install Nodemon globally, use the following command.
npm install -g nodemon

Step 3. Verify Installation

You can use the next command to verify that Nodemon has been correctly installed.
nodemon -v


How to fix the nodemon command that is not recognized in the terminal for Node.js?

The "Nodemon command is not recognized" error can be annoying, but have no worry — it's a common problem with a simple fix. In this section, we'll walk you through the procedures to fix the issue and set up Nodemon on your machine.

Step 1. Install npm
To install npm, use the following command.
npm install

Step 2. Update package.json file
To update package.json, use the following scripts.
"scripts": {
    "server": "nodemon index.js"
  },


Step 3. Run project
To run the project, use the following commands.
npm run server

Conclusion
Installing Nodemon and fixing the typical "Nodemon command is not recognized" problem are two essential components of Node.js development that have been covered in this article. Nodemon is a useful tool for streamlining development efficiency by automatic server restarts following code changes. To ensure you can exploit Nodemon's features to the fullest, the "How to Install Nodemon in Node.js" section offers a detailed tutorial. The section titled "How to Fix Nodemon Command Is Not Recognized in the Terminal for Node.js" also addresses the annoying "Nodemon command is not recognized" error and offers workable alternatives. With these tips, your Node.js development process will go more smoothly and effectively, allowing you to concentrate on writing code while Nodemon takes care of the rest.



Node.js Hosting - HostForLIFE :: Create a Node Environment and Run a Simple Node Server Project

clock September 13, 2023 10:07 by author Peter

In this article, we'll look at how to use Node.js to create a web application. Let's take it one step at a time.

Step 1: Download NodeJS from the NodeJS website.
Download the Windows Installer from the Nodejs website. Check that you have the most recent version of NodeJs. It comes with the NPM package management. Install node js already and skip the preceding step.

Step 2: Ensure that Node and NPM are installed and that their PATHs are configured.

Check If you're not sure whether you installed everything correctly, use "Command Prompt" to double-check.

To verify the installation and confirm whether the correct version was installed,

Enter the following command to Check the node version.
Node --version or Node -v

Check the npm version, and run this command:
npm --version or npm -v

Step 3. Create a new project
You can create a project folder wherever you want on your computer and name it whatever you want.

Step 4. Create a new js file
Create a .js File By using the .js file extension

I Create an app.js file in the project folder. Create a simple string variable in app.js and send the contents of the string to the console: save the file.
var message= “Hi C# Corner”;
console.log(message);


Step 5. Run the App
It's simple to run app.js with Node.js. From a terminal, just type: Node .\app.js

You can see the "Hi C# Corner" output to the terminal, and then Node.js returns

Step 6. Install NPM Packages
install npm package Go to the terminal and type npm init -y this command line, we highlight -y when we install in npm' npm init' Does that time ask a question: package name? We can give the package name as yourself. Otherwise, it takes the default name Project Folder Name. If entered, the command line npm init -y takes the saver name as the default.

I'm going to run this Project in package.js, So I have to add a line in scripts at package.js "serve": "node app.js".
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "serve": "node app.js"
  },

I'm going to run the application with this command npm run serve.


What Is Express JS?    
Express is a node js web application framework that provides broad features for building web and mobile applications. It is used to build a single page, multipage, and hybrid web application.

Features of Express Framework
Allows to set up middlewares to respond to HTTP Requests.
Defines a routing table that is used to perform different actions based on HTTP Method and URL.
Allows to dynamically render HTML Pages based on passing arguments to templates
npm install express or npm i express

I recommend the nodemon package for Node. js-based applications by automatically restarting the node application when the file changes in the directory are detected.

nodemon will be installed globally on your system path.
npm install -g nodemon # or using yarn: yarn global add nodemon

Step 8. Write down the following code in the app.js file
const express = require("express");
const app = express();
const port = 3000;

//routes
app.get("/", (req, res) => {
  res.send("HI C# Corner!");
});


app.listen(port, () => {
  console.log(`My Sample Nodejs App Listening On Port ${port}`);
});


Following is a very basic Express app that starts a server and listens on port 3000 for the connection.
app.listen(port, () =>
{console.log(`My Sample Nodejs App Listening On Port ${port}`)
})


The app responds with "HI C# Corner!" for requests to the root URL (/) or route.
app.get('/', (req, res) => {
  res.send('HI C# Corner!')
})


`npm run serve`

This app starts a server and listens on port 3000 for connections.

Step 9. Now you can see the output on your browser
Now go to http://localhost:3000/ in the browser, and you will see the following output:

In this article, we will learn how to create a Node project and how we can develop a web application using Node.js. It is a runtime environment and library for running JavaScript code outside the browser. It must be installed on the system by downloading the software from the Node.js website and setting the path in the environment variables section.



Node.js Hosting Europe - HostForLIFE.eu :: Image Generation Using OpenAI API and Node.js

clock July 6, 2023 09:26 by author Peter

DALL-E, developed by OpenAI, is an AI model that can generate images from textual descriptions. It combines the power of deep learning and generative modeling to create unique and imaginative visual outputs based on the provided text prompts. This technology has sparked excitement among researchers, artists, and developers alike.


To make the capabilities of DALL-E accessible to developers, OpenAI has released the DALL-E API. This API allows developers to interact with the DALL-E model programmatically; by using this, developers can generate images by giving text prompts. By using Node.js and  DALL-E, we can generate images programmatically.

Note. If you want to achieve this using Python, Please read my previous article on how to Generate Image Using DALL-E API and Python.

Prerequisites
It is essential to have a basic understanding of the following concepts and technologies.

Node.js
Node.js is a JavaScript runtime environment that allows you to run JavaScript code outside of a web browser. To use Node.js, you'll need to install it on your machine. Install Node.js from the official website.

Basic API Concepts

A basic understanding of API (Application Programming Interface) concepts is crucial. APIs provide a way for different software applications to communicate and exchange data. Familiarize yourself with concepts like endpoints, HTTP methods (GET, POST, etc.), request/response structure, and how to handle API responses using JavaScript.

Setting Up the Project

Open your terminal or command prompt and follow these steps.
    Create a new directory for your Project.
    mkdir dalle-image
    cd dalle-image


Initialize a new Node.js project by running the following command.
npm init -y

This will create a package.json file, keeping track of your Project's dependencies.

Install Required Dependencies
Install the Axios library to make API requests to the DALL-E API. Axios is a popular JavaScript library for making HTTP requests. It simplifies the process of sending asynchronous requests and handling responses. To install it, use the following command
npm install axios

Now, Axios is added to your Project's dependencies, and you can start using it to interact with the DALL-E API.

Writing the Node.js Code

Write the code to interact with the DALL-E API using Node.js. Follow the steps below.

Setting up the API Endpoint and Authorization

Navigate to the dalle-image directory and create a new JavaScript file, for example, dalle-api.js.
Require the Axios module at the top.
const axios = require('axios');

Next, declare a constant variable to store your DALL-E API key.
const API_KEY = 'YOUR_API_KEY';

Implementing the API Call using Axios
Implement the API call using Axios.
const axios = require('axios');
const API_KEY = 'YOUR_API_KEY';   //replace with your key

const generateImages = async () => {
  try {
    const response = await axios.post(
      'https://api.openai.com/v1/images/generations',
      {
        prompt: 'A beautiful sunset over a serene lake',
        n: 1,                                //define the number of images
        size: '512x512',                     //define the resolution of image
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${API_KEY}`,
        },
      }
    );

    console.log(response.data);
    // Handle the response here, e.g., extract image data and display or save it.
  } catch (error) {
    console.error('Error:', error.response.data);
  }
};

generateImages();


In the code above, we use the Axios. post method to make a POST request to the API endpoint. We pass the request payload as the second argument to the method and include the API key in the request headers.

Now run the Project using the following command.
node dalle-api.js

Check the console output to see the API response or any errors that occurred during the process.

Output



Node.js Hosting - HostForLIFE :: .Net Core Vs Node

clock February 15, 2023 09:18 by author Peter

.NET Core and Node.js are two popular technologies for building APIs (Application Programming Interfaces). Both have their strengths and weaknesses, and the choice between them depends on the specific requirements of a project.

.NET Core is a cross-platform, open-source framework for building modern applications. It is developed by Microsoft and is part of the .NET ecosystem. .NET Core is based on C#, a statically-typed language. It supports LINQ (Language Integrated Query) and Entity Framework, making it easier to query data. .NET Core also provides a strong security model, built-in support for WebSockets, and the ability to run on Windows, Linux, and macOS.

Node.js, on the other hand, is an open-source, cross-platform JavaScript runtime environment. It is event-driven and non-blocking, making it highly efficient for real-time applications. Node.js has a vast and growing ecosystem, with numerous packages and tools available for a variety of purposes, including building APIs.

When it comes to building APIs, .NET Core is a good choice if you're looking for a framework with a strong security model, good performance, and the ability to handle large amounts of data. .NET Core is also a good choice if you're already familiar with C# and the .NET ecosystem, as this will reduce the learning curve.

Node.js, on the other hand, is a good choice if you're looking for a fast and efficient API that can handle real-time data and can be scaled horizontally. Node.js is also a good choice if you're already familiar with JavaScript and the Node.js ecosystem, as this will reduce the learning curve.

Similarities between .Net Core and Node

Despite their differences, .NET Core and Node.js have some similarities as well. Here are some of the most notable similarities between the two technologies:

Cross-platform compatibility
Both .NET Core and Node.js are cross-platform technologies, which means that they can run on multiple operating systems, including Windows, Linux, and macOS.

Open-source

Both .NET Core and Node.js are open-source technologies, which means that their source code is available for anyone to use, modify, or contribute to.

Large and active communities
Both .NET Core and Node.js have large and active communities of developers, which means that there is a wealth of knowledge, tools, and resources available for these technologies.

Fast and efficient

Both .NET Core and Node.js are designed to be fast and efficient, making them well-suited for building high-performance applications, including APIs.

Support for modern web technologies
Both .NET Core and Node.js support modern web technologies, such as REST and WebSockets, making it easy to build modern, scalable APIs.

Difference between .Net Core and Node

While .NET Core and Node.js have some similarities, they also have some notable differences that make them well-suited for different types of projects. Here are some of the most important differences between the two technologies,

Language
.NET Core is based on C#, a statically-typed language, while Node.js is based on JavaScript, a dynamically-typed language. This can impact the development experience and the performance of the resulting application.

Performance

.NET Core is generally considered to be a more performant framework, especially for applications that require handling large amounts of data. Node.js, on the other hand, is designed for real-time, event-driven applications and is highly efficient for these types of applications.

Ecosystem
.NET Core is part of the .NET ecosystem, which includes a large number of libraries, tools, and frameworks for building applications. Node.js has a growing and vibrant ecosystem of its own, with a large number of packages and tools available for a wide range of purposes.

Security
.NET Core provides a strong security model, with built-in support for authentication, authorization, and encryption. Node.js, while secure, does not provide the same level of security features out-of-the-box as .NET Core.

Scalability
Node.js is designed to be highly scalable, with the ability to run multiple instances of the application on multiple machines to handle increased traffic. .NET Core also supports scalability, but it may require additional work to achieve the same level of scalability as Node.js.

.NET Core and Node.js are both powerful technologies for building APIs, but they have some important differences that make them well-suited for different types of projects. The choice between the two will depend on the specific requirements of a project, including the desired performance, security, scalability, and skills of the development team.

In conclusion, despite the differences between .NET Core and Node.js, the two technologies have some similarities, including cross-platform compatibility, open-source nature, large and active communities, fast and efficient performance, and support for modern web technologies.

Conclusion

In conclusion, the choice between .NET Core and Node.js depends on the specific requirements of a project. .NET Core is a good choice for projects that require a strong security model and good performance, while Node.js is a good choice for projects that require real-time data and scalability. Before making a choice, it is important to consider the specific requirements of a project and the skills of the development team.

Thanks for reading my article.



Node.js Hosting - HostForLIFE.eu :: How To Setup A Express.js Project?

clock January 6, 2023 06:36 by author Peter

Express.js is one of the most popular frameworks for building web applications using Node.js. It provides features that make creating a robust and scalable web application easy. This step-by-step guide will go over all the steps for setting up an Express.js project from scratch.

Installation is pretty straightforward. Before we get started, you will need to have Node.js installed on your system. You can download the latest version of Node.js from the official website. Once installation is complete, you can run the following commands to verify if Node.js and npm are working correctly on your computer.
npm -v

node -v

You're good to go if you see the versions of Node.js and npm in the command line.

Initializing the project
Let's start by creating a new directory for your project and navigate to it:
mkdir my-express-project
cd my-express-project

Next, initialize the Node.js project by running the following command:
npm init -y

This will create a package.json file in your project directory. The package.json file stores metadata about your project, including the dependencies it needs to run. the -y parameter is used to skip the questionnaire altogether. It'll implicitly set yes to all the questions during the npm init command.

Installing Express.js
To install Express.js, run the following command:
npm install express

This will install Express.js and add it as a dependency in your package.json file.

Creating an entry point for the application
Next, we'll create an entry point for your application. This file will be run when you start the application. First, let's create an src directory in the root of our application and then create a file called index.js inside the src folder and add the following code inside that file:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
    res.send('Hello Express!');
});
app.listen(port, () => {
    console.log(`App is running on port ${port}`);
});

The above code creates an instance of an Express.js app and sets up a route that listens for GET requests to the app's root path (/). When a request is received, it sends a response with the message "Hello Express!". The application is also set to listen on port 3000.

Adding start script
Next, open your package.json file and add look for scripts section. In this section, add the following script.
"scripts": {
  "start": "node src/index.js"
},

Starting the app

Now from the root of your application, run the following command
npm start

This will start the app, and you should see the message "App is running on port 3000" in the console.
To test the app, open your web browser and navigate to http://localhost:3000. You should see the message "Hello Express!" displayed in the browser.

And That's it! I hope you found this article enjoyable. If you've any queries or feedback, feel free to comment.



Node.js Hosting Europe - HostForLIFE :: Overview And Explore NestJS

clock November 22, 2022 09:21 by author Peter

This would be a series of articles and in this article, we would talk about NestJS, its background, installation, and how it can be used to build APIs.


It will cover the following things,
    What is NestJS?
    Background
    Installation
    Hands-on Lab – Create a sample NestJS project

What is NestJS?
    NestJS is fairly a popular and cumulative JavaScript framework functioning under the hood of Node.js
    It is used to build scalable, reliable, and efficient server-side applications.
    The framework is directed with the Node.js environment and supports Typescript fully.
    It also can be scaled to make use of Express.js under the influence of Node.js
    NestJS is a full Typescript-supported framework, it can enable developers like you to code purely in JavaScript
    Also, it would let you combine the concepts of Object-Oriented Programming(OOP), Functional Reactive Programming(FRP), and purely Functional Programming(FP).

Background

    NestJS makes use of heavy usage of the server-side framework like Express under the hood of robust HTTP infrastructure.
    It can also be optionally configured to make use of Fastify as well although Express is considered as default.
    NestJS aims to provide a certain level of abstraction mechanism to the developers so that not only the common server-side frameworks like Fastify or Express are integrated internally but can also be exposed to the APIs chosen by the developer.
    These hidden bars provide developers to gain the freedom to use the third-party modules brightly and they can be made to motivate in the NestJS platform without having to operate the entire server side.

Installation

    All you need to do is to make sure you have Nest CLI is primarily installed on your local computer.
    If it is not installed, make use of the Node Package Manager (NPM) and follow up the approach using the commands given below.
    Also, you would need to make sure Node.js and NPM are preinstalled in your local system. If not, just follow the instructions to install Node.js at https://nodejs.org/
    $ npm i –g @nestjs/cli

Hands-on Lab – Create a sample NestJS project

Steps to be followed,
    Once the NestJS CLI installation is marked complete, it will readily be available to use the commands.
    Now let’s proceed with creating a sample project, and use the following control to initialize it.

    nest new nestjs-demo

    cd nestjs-demo

    Open Visual Code and see the project structure with the following files -

    main.ts - It is the application's entry point which consists of a method NestFactory.create() which creates a new instance of the Nest application.
    app.modules.ts: It contains the module of the application's implementation.
    app.controller.ts: It consists of only one routed implementation controller of NestJS.
    app.services.ts: It is the usual service method implementation.
    app.controller.specs.ts: It tests the file for the controller.

    Run the application by executing the below command and look at the browser with the output.

In this article, we talked about the overview and basic implementation of NestJS, in the next article, we would talk about all the out-of-the-box files in detail and create a few custom APIs. Stay tuned for the next series of articles, hope you see you guys again soon.

Happy learning!



Node.js Hosting Europe - HostForLIFE ::Middleware In Node.js

clock September 27, 2022 09:10 by author Peter

What is middleware and how to use middleware in node.js with express.js
Middleware is a piece of code (function) that is used to execute some code after the server gets a call from a client and before the controller action which will send a response. So it means that whenever a client will call an API, before reaching the request to that API (route), middleware code will be executed.


Middleware is used for different purposes like logging requests, and verifying requests for some specific requirement. Like in this article, we will be using middleware to verify if some specific key is present in the request headers or not.

Creating a Node server using express.js
For creating a node.js server, go to a folder and open vscode in it. Run the command npm init to initialize the node.js project. It will create a package.json file in your root directory. Then command npm install express to install express.js which we will use to create our server.

Optionally, run the command npm install nodemon this will install nodemon in your project. Nodemon is used to auto-refresh your node.js project without starting the server again and again.

In the package.json file, update the scripts tag as follows:
//if nodemon is installed
"scripts": {
        "start": "nodemon index.js"
},
//if nodemon is not installed
"scripts": {
        "start": "node index.js"
},

Then in your root directory, create a file app.js and add the following code to it.
const express = require("express");
const app = express();

app.get("/", (req, res) => {
  res.send("Home Page");
});

app.get("/users", (req, res) => {
  res.send("Users Page");
});

app.listen(3000, () => console.log(`Server is started at port 3000`));


Creating the middleware
In node.js, middleware has three parameters req, res, and next. Next is very important here. When we process our logic in the middleware then at the end we have to call next() so that call can react to the desired route.

We will be creating a middleware that will check every request and verify if some specific key (some-key in our case) is present in the header or not. If a key is there, then it will pass the request to the route otherwise it will reject the call and send the response that the request is invalid.

Create a folder with the name middleware (you can give any name but the code I am using for this article have this name) and add a file middleware.js in it. Then add the following code in the file.
function headersVerificationMiddleware(req, res, next) {
  if (!req.headers["some-key"]) {
    console.log("Invalid request");
    res.send("Invalid request");
  }
  console.log("Inside Middleware");
  next();
}


module.exports = headersVerificationMiddleware;

Then update your app.js code according to the following code.
const express = require("express");
const app = express();

//adding middleware
const headersVerificationMiddleware = require("./middleware");
app.use(headersVerificationMiddleware);

app.get("/", (req, res) => {
  res.send("Home Page");
});

app.get("/users", (req, res) => {
  res.send("Users Page");
});

app.listen(3000, () => console.log(`Server is started at port 3000`));


Output without passing the some-key in HTTP headers.


Output with some-key in HTTP headers

Some key points about Middlewares
 
1. Middlewares are similar to controller actions (routes)
Controller actions which have req, and res variables are similar to middleware. The only difference is that middleware also has a variable next which will be called at the end of middleware. It is not necessary for the next() method to be called at the end of the middleware method. It can be used anywhere in the middleware where the next route needs to be called.

2. Middleware work in order
Middleware work in the same order in which they are defined in the app.js file. For example, there are two middleware MiddlewareA and MiddlewareB these both will be called in order. First MiddlewareA will be executed and then MiddlewareB will be executed.



Node.js Hosting Europe - HostForLIFE :: How To Check If A File Exists In NodeJS?

clock July 6, 2022 10:29 by author Peter

Node.js comes bundled with the file system module which allows the developers to interact with the file system of the operating system. This module is commonly used to create, read, update, delete and rename a file. However, before we start performing the above-mentioned operations it is always a better idea to check if the file we're trying to access exists in the file system. And the file system module provides multiple ways to perform this check.
Using existsSync method

The easiest way to test if a file exists in the file system is by using the existsSync method. All you need to do is pass the path of the file to this method.
const fs = require('fs');
const path = './my-awesome-file.txt';

if (fs.existsSync(path)) {
  console.log('file exists');
} else {
  console.log('file not found!');
}


The existsSync method will return true if the file exists and else it'll return false.
One thing that we need to keep in mind is this method is synchronous in nature. that means that it’s blocking.

Using exists method (Deprecated)
The exists method checks for the existence of a file asynchronously. It accepts two parameters:
    Path to the file
    Callback function to execute once path is verified passing a boolean parameter value to the function as its argument.
const fs = require('fs');
const path = './my-awesome-file.txt';

fs.exists(path, function (doesExist) {
  if (doesExist) {
    console.log('file exists');
  } else {
    console.log('file not found!');
  }
});


The parameter value will be true when the file exists otherwise it'll be false.

Using accessSync method
The accessSync method is used to verify the user’s permission for the specified path. If the path is not found, it will throw an error that we need to handle using try...catch block.

This method accepts two parameters as follows,
    Path to the file
    Mode of verification

The mode parameter is optional. It specifies the accessibility checks that need to be performed.0

Following constants can be used as the second parameter to specify the mode.
      fs.constants.R_OK to check for read permission
    fs.constants.W_OK to check for write permission
    fs.constants.X_OK to check for execute permission

If the second parameter is not provided it defaults to  fs.constants.F_OK constant.
const fs = require('fs');
const path = './my-awesome-file.txt';

try {
  fs.accessSync(path);
  console.log('file exists');
} catch (err) {
  console.log('file not found');
  console.error(err);
}

The above code verifies the existence of my-awesome-file.txt file:

If you wish to determine the write and read access, you can pass the mode parameter with a bitwise OR operator as follows:
const fs = require('fs');
const path = './my-awesome-file.txt';

try {
  fs.accessSync(path, fs.constants.R_OK | fs.constants.W_OK);
  console.log('read/write access');
} catch (err) {
  console.log('no access:');
  console.error(err);
}


Using access method
The access method is basically the asynchronous version of accessSync method.

The access method allows the developers to verify the existence or permissions of a specified path asynchronously.

The method accepts three parameters, first two parameters are the same as accessSync method parameters, and last parameter is a callback function:
    Path to the file
    Mode of verification
    The callback function to execute

const fs = require('fs')
const path = './my-awesome-file.txt'

fs.access(path, fs.F_OK, (err) => {
  if (err) {
    console.error(err)
    return;
  } else {
    console.log('file exists')
  }
})


existsSync, exists, accessSync, and access are the four methods that allow the developers to verify if the file exists in the file system. It’s recommended to use existsSync method if you only wish to check for the existence of a file. When you wish to check for specific permissions as well as the existence of the file, you can use either accessSync or access method. The exists method is deprecated from node.js and hence needs to be avoided. 



Node.js Hosting - HostForLIFE :: How To Check If A File Exists In NodeJS?

clock June 14, 2022 10:31 by author Peter

Node.js comes bundled with the file system module which allows the developers to interact with the file system of the operating system. This module is commonly used to create, read, update, delete and rename a file. However, before we start performing the above-mentioned operations it is always a better idea to check if the file we're trying to access exists in the file system. And the file system module provides multiple ways to perform this check.

Using existsSync method
The easiest way to test if a file exists in the file system is by using the existsSync method. All you need to do is pass the path of the file to this method.
const fs = require('fs');
const path = './my-awesome-file.txt';

if (fs.existsSync(path)) {
  console.log('file exists');
} else {
  console.log('file not found!');
}


The existsSync method will return true if the file exists and else it'll return false.
    One thing that we need to keep in mind is this method is synchronous in nature. that means that it’s blocking.

Using exists method (Deprecated)
The exists method checks for the existence of a file asynchronously. It accepts two parameters:

    Path to the file
    Callback function to execute once path is verified passing a boolean parameter value to the function as its argument.

const fs = require('fs');
const path = './my-awesome-file.txt';

fs.exists(path, function (doesExist) {
  if (doesExist) {
    console.log('file exists');
  } else {
    console.log('file not found!');
  }
});

The parameter value will be true when the file exists otherwise it'll be false.

Using accessSync method
The accessSync method is used to verify the user’s permission for the specified path. If the path is not found, it will throw an error that we need to handle using try...catch block.

This method accepts two parameters as follows,
    Path to the file
    Mode of verification

The mode parameter is optional. It specifies the accessibility checks that need to be performed.0

Following constants can be used as the second parameter to specify the mode.
    fs.constants.R_OK to check for read permission
    fs.constants.W_OK to check for write permission
    fs.constants.X_OK to check for execute permission


If the second parameter is not provided it defaults to  fs.constants.F_OK constant.
const fs = require('fs');
const path = './my-awesome-file.txt';

try {
  fs.accessSync(path);
  console.log('file exists');
} catch (err) {
  console.log('file not found');
  console.error(err);
}

The above code verifies the existence of my-awesome-file.txt file:

If you wish to determine the write and read access, you can pass the mode parameter with a bitwise OR operator as follows:
const fs = require('fs');
const path = './my-awesome-file.txt';

try {
  fs.accessSync(path, fs.constants.R_OK | fs.constants.W_OK);
  console.log('read/write access');
} catch (err) {
  console.log('no access:');
  console.error(err);
}

Using access method
The access method is basically the asynchronous version of accessSync method.

The access method allows the developers to verify the existence or permissions of a specified path asynchronously.

The method accepts three parameters, first two parameters are the same as accessSync method parameters, and last parameter is a callback function:
    Path to the file
    Mode of verification
    The callback function to execute

const fs = require('fs')
const path = './my-awesome-file.txt'

fs.access(path, fs.F_OK, (err) => {
  if (err) {
    console.error(err)
    return;
  } else {
    console.log('file exists')
  }
})


existsSync, exists, accessSync, and access are the four methods that allow the developers to verify if the file exists in the file system. It’s recommended to use existsSync method if you only wish to check for the existence of a file. When you wish to check for specific permissions as well as the existence of the file, you can use either accessSync or access method. The exists method is deprecated from node.js and hence needs to be avoided. 



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Tag cloud

Sign in