Full Trust European Hosting

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

Node.js Hosting - HostForLIFE :: Pass parameter to Node.js application from command prompt

clock May 28, 2021 08:06 by author Peter

You can get command-line arguments passed to your node.js application by using process.argv. process.argv is actually an array. So if you want values, out of this array you'll either have to use a loop or you can get simply by putting array index in process.argv.


Suppose you have a node.js app. "myscript.js".

You have passed parameters as:
    $node myscript.js 4

Then in the code as in line number 2 of below code, we can get the parameter value as process.argv[2].
    function GetSqrt() {  
        var num = process.argv[2];  
        console.log(" Number is " + num + " and its square " + num * num);  
    }  
    GetSqrt();


You might be thinking, why I have given index number 2 and not 0. Actually process.argv[0] will return 'node' and process.argv[1] will return your script name as in this case myscript.js.

If you have multiple arguments to pass from the command prompt, you can create a separate method for argument parsing as like
    function GetSqrt() {  
       var args = ParseArguments();  
       args.forEach(function(num) {  
      
           console.log(" Number is " + num + " and its square " + num * num);  
       })  
    }  
    GetSqrt();  
      
    function ParseArguments() {  
       var input = [];  
       var arguments = process.argv;  
       arguments.slice(2).forEach(function(num) {  
           input.push(num);  
       });  
       return input;  
    }


Here arguments.slice(2) will remove first two arguments(node and your application name) from arguments array



Node.js Hosting - HostForLIFE :: Integrate Open API (Swagger) With Node And Express

clock May 18, 2021 12:41 by author Peter
This article will explain how to integrate swagger (Open API) with Node & express. Swagger makes it very easy for a backend developer to document, test, and explain API endpoints he/she's been working on a front-end developer or anyone looking to consume those endpoints.

Setup
Before we get started into this we should have few things installed in our machine.
    Visual Studio Code -> Visual Studio Code
    Node.js -> Node.js

Source Code - Git Code
Required Packages
npm init
npm install swagger-jsdoc swagger-ui-express express nodemon

 
Express - For Server
 
Swagger - For API's Documentation in UI
 
Nodemon - will use this to restart our server automatically whenever we make changes to our files.
 
After installing the required packages let's add the new file to set up the Swagger configuration and as well adding the API endpoints in Node
 
Structure of the Project

Setting up the swagger
Swagger UI can be set up for both the front end & backend as well. Since this article is about the Swagger with Node.js. I will be setting up the the swagger in Node.js express app only. you can explore the other options here
 
In your api.js
    //Swagger Configuration  
    const swaggerOptions = {  
        swaggerDefinition: {  
            info: {  
                title:'Employee API',  
                version:'1.0.0'  
            }  
        },  
        apis:['api.js'],  
    }  
    const swaggerDocs = swaggerJSDoc(swaggerOptions);  
    app.use('/api-docs',swaggerUI.serve,swaggerUI.setup(swaggerDocs));  

       
After integrating the swagger setup lets define the swagger endpoint with description and response codes in a particular format so that we can able to access those API's inside the swagger after running in the browser
 
Add Swagger Before Each End Point
    /**
     * @swagger
     * /Employees:
     *   get:
     *     description: Get all Employee
     *     responses:  
     *       200:
     *         description: Success  
     *   
     */  
    app.get('/Employees',(req,res)=>{  
        res.send([  
            {  
                id:1, Name:'Jk'  
            },  
            {  
                id:2,Name:'Jay'  
            }  
        ])  
    });  

For the demo purpose, I have added four API's (Get, Post, Put, Delete) added the swagger setup for the remaining endpoints as well
 
Final api.js
    const express = require('express');  
    const swaggerJSDoc = require('swagger-jsdoc');  
    const swaggerUI = require('swagger-ui-express');  
      
    const app = express();  
      
    app.listen(5000,()=>console.log("listening on 5000"));  
      
    //Swagger Configuration  
    const swaggerOptions = {  
        swaggerDefinition: {  
            info: {  
                title:'Employee API',  
                version:'1.0.0'  
            }  
        },  
        apis:['api.js'],  
    }  
    const swaggerDocs = swaggerJSDoc(swaggerOptions);  
    app.use('/api-docs',swaggerUI.serve,swaggerUI.setup(swaggerDocs));  
       
    /**
     * @swagger
     * /Employees:
     *   get:
     *     description: Get all Employee
     *     responses:  
     *       200:
     *         description: Success  
     *   
     */  
    app.get('/Employees',(req,res)=>{  
        res.send([  
            {  
                id:1, Name:'Jk'  
            },  
            {  
                id:2,Name:'Jay'  
            }  
        ])  
    });  
      
    /**
     * @swagger
     * /Employees:
     *   post:
     *     description: Create an Employee
     *     parameters:
     *     - name: EmployeeName
     *       description: Create an new employee
     *       in: formData
     *       required: true
     *       type: String
     *     responses:  
     *       201:
     *         description: Created  
     *   
     */  
     app.post('/Employees',(req,res)=>{  
       res.status(201).send();  
    });  
    /**
     * @swagger
     * /Employees:
     *   put:
     *     description: Create an Employee
     *     parameters:
     *     - name: EmployeeName
     *       description: Create an new employee
     *       in: formData
     *       required: true
     *       type: String
     *     responses:  
     *       201:
     *         description: Created  
     *   
     */  
     app.put('/Employees',(req,res)=>{  
        res.status(201).send();  
     });  
     /**
     * @swagger
     * /Employees:
     *   delete:
     *     description: Create an Employee
     *     parameters:
     *     - name: EmployeeName
     *       description: Create an new employee
     *       in: formData
     *       required: true
     *       type: String
     *     responses:  
     *       201:
     *         description: Created  
     *   
     */  
      app.delete('/Employees',(req,res)=>{  
        res.status(201).send();  
     });  


Run the URL in the browser
Now you can do the npm start in the terminal to your app and it will navigate to the browser we have to add the /api-docs at the end of the URL so that i will navigate to the swagger which we have configured and you will see the Swagger UI based on your generated swagger.json.
 
Terminal

Swagger


Testing the API with Swagger



Node.js Hosting - HostForLIFE :: Integrate Open API (Swagger) With Node And Express

clock May 18, 2021 12:41 by author Peter
This article will explain how to integrate swagger (Open API) with Node & express. Swagger makes it very easy for a backend developer to document, test, and explain API endpoints he/she's been working on a front-end developer or anyone looking to consume those endpoints.

Setup
Before we get started into this we should have few things installed in our machine.
    Visual Studio Code -> Visual Studio Code
    Node.js -> Node.js

Source Code - Git Code
Required Packages
npm init
npm install swagger-jsdoc swagger-ui-express express nodemon

 
Express - For Server
 
Swagger - For API's Documentation in UI
 
Nodemon - will use this to restart our server automatically whenever we make changes to our files.
 
After installing the required packages let's add the new file to set up the Swagger configuration and as well adding the API endpoints in Node
 
Structure of the Project

Setting up the swagger
Swagger UI can be set up for both the front end & backend as well. Since this article is about the Swagger with Node.js. I will be setting up the the swagger in Node.js express app only. you can explore the other options here
 
In your api.js
    //Swagger Configuration  
    const swaggerOptions = {  
        swaggerDefinition: {  
            info: {  
                title:'Employee API',  
                version:'1.0.0'  
            }  
        },  
        apis:['api.js'],  
    }  
    const swaggerDocs = swaggerJSDoc(swaggerOptions);  
    app.use('/api-docs',swaggerUI.serve,swaggerUI.setup(swaggerDocs));  

       
After integrating the swagger setup lets define the swagger endpoint with description and response codes in a particular format so that we can able to access those API's inside the swagger after running in the browser
 
Add Swagger Before Each End Point
    /**
     * @swagger
     * /Employees:
     *   get:
     *     description: Get all Employee
     *     responses:  
     *       200:
     *         description: Success  
     *   
     */  
    app.get('/Employees',(req,res)=>{  
        res.send([  
            {  
                id:1, Name:'Jk'  
            },  
            {  
                id:2,Name:'Jay'  
            }  
        ])  
    });  

For the demo purpose, I have added four API's (Get, Post, Put, Delete) added the swagger setup for the remaining endpoints as well
 
Final api.js
    const express = require('express');  
    const swaggerJSDoc = require('swagger-jsdoc');  
    const swaggerUI = require('swagger-ui-express');  
      
    const app = express();  
      
    app.listen(5000,()=>console.log("listening on 5000"));  
      
    //Swagger Configuration  
    const swaggerOptions = {  
        swaggerDefinition: {  
            info: {  
                title:'Employee API',  
                version:'1.0.0'  
            }  
        },  
        apis:['api.js'],  
    }  
    const swaggerDocs = swaggerJSDoc(swaggerOptions);  
    app.use('/api-docs',swaggerUI.serve,swaggerUI.setup(swaggerDocs));  
       
    /**
     * @swagger
     * /Employees:
     *   get:
     *     description: Get all Employee
     *     responses:  
     *       200:
     *         description: Success  
     *   
     */  
    app.get('/Employees',(req,res)=>{  
        res.send([  
            {  
                id:1, Name:'Jk'  
            },  
            {  
                id:2,Name:'Jay'  
            }  
        ])  
    });  
      
    /**
     * @swagger
     * /Employees:
     *   post:
     *     description: Create an Employee
     *     parameters:
     *     - name: EmployeeName
     *       description: Create an new employee
     *       in: formData
     *       required: true
     *       type: String
     *     responses:  
     *       201:
     *         description: Created  
     *   
     */  
     app.post('/Employees',(req,res)=>{  
       res.status(201).send();  
    });  
    /**
     * @swagger
     * /Employees:
     *   put:
     *     description: Create an Employee
     *     parameters:
     *     - name: EmployeeName
     *       description: Create an new employee
     *       in: formData
     *       required: true
     *       type: String
     *     responses:  
     *       201:
     *         description: Created  
     *   
     */  
     app.put('/Employees',(req,res)=>{  
        res.status(201).send();  
     });  
     /**
     * @swagger
     * /Employees:
     *   delete:
     *     description: Create an Employee
     *     parameters:
     *     - name: EmployeeName
     *       description: Create an new employee
     *       in: formData
     *       required: true
     *       type: String
     *     responses:  
     *       201:
     *         description: Created  
     *   
     */  
      app.delete('/Employees',(req,res)=>{  
        res.status(201).send();  
     });  


Run the URL in the browser
Now you can do the npm start in the terminal to your app and it will navigate to the browser we have to add the /api-docs at the end of the URL so that i will navigate to the swagger which we have configured and you will see the Swagger UI based on your generated swagger.json.
 
Terminal

Swagger


Testing the API with Swagger



AngularJS Hosting Europe - HostForLIFE.eu :: Angular 11 Spinner/Loader With Out Any Third Party Library/Package

clock May 4, 2021 06:38 by author Peter

In this article, we will learn how we can show the Loader in Angular 11 without using any third-party spinner. We are using CSS to build an animated Spinner.

 

Step 1
Create an Angular project by using the following command
 
ng new Angularloader
 
Step 2
Open this project in Visual Studio Code and install bootstrap by using the following command
npm install bootstrap --save
 
Step 3

Jquery is needed to run bootstrap click events. So install jquery using below command
npm install jquery --save
 
Declare Jquery before bootstrap.
 
Otherwise, you will get the below error
Uncaught TypeError: Bootstrap's JavaScript requires jQuery. jQuery must be included before Bootstrap's JavaScript.

    "scripts": [  
    "node_modules/jquery/dist/jquery.js",  
    "node_modules/bootstrap/dist/js/bootstrap.js"]   


Now Bootstrap will work fine.
 
Step 4
    Let's start the main goal of the articlet to show spinner.
    Create one new component using Ng g c popuploader
    In popuploader.component.css file paste below lines of code to create animated spinner
        .loadWrapper {  
            background: rgba(0, 0, 0, 0.3);  
            width: 100 % ;  
            height: 100 % ;  
            position: fixed;  
            top: 0 px;  
            left: 0 px;  
            z - index: 99999;  
        }.loader {  
            border: 5 px solid #f3f3f3; /* Light grey */  
            border - top: 5 px solid #3d3e3f; /* gray */  
           position: absolute;  
           left: 50%;  
           top: 50%;  
           border-radius: 50%;  
           width: 50px;  
           height: 50px;  
           animation: spin 2s linear infinite;  
        }  
        @keyframes spin {  
           0% { transform: rotate(0deg); }  
           100% { transform: rotate(360deg); }  
        }  


Step 5

We will create one simple data service which will load data into table..For that I have created student.service.ts file
 
In StudentService write the below line of code.
    import {  
        Injectable  
    } from '@angular/core';  
    @Injectable({  
        providedIn: 'root'  
    })  
    export class StudentService {  
        students = [{  
            "id": 1001,  
            "name": "Peter",  
            "marks": 90  
        }, {  
            "id": 1002,  
            "name": "Scott",  
            "marks": 80  
        }, {  
            "id": 1003,  
            "name": "Mark",  
            "marks": 70  
        }, {  
            "id": 1004,  
            "name": "Tom",  
            "marks": 85  
        }, {  
            "id": 1005,  
            "name": "Alice",  
            "marks": 60  
        }];  
        constructor() {}  
        getStudents() {  
            return this.students;  
        }  
    }   


Step 6

Lets call this service in our popuploader component
    import {  
        Component,  
        OnInit  
    } from '@angular/core';  
    import {  
        StudentService  
    } from '../student.service';  
    @Component({  
        selector: 'app-popuploader',  
        templateUrl: './popuploader.component.html',  
        styleUrls: ['./popuploader.component.css']  
    })  
    export class PopuploaderComponent implements OnInit {  
        public loading = true;  
        public studentList: any[];  
        constructor(private stnService: StudentService) {}  
        ngOnInit() {  
            this.loading = true;  
            setTimeout(() => {  
                /** spinner ends after 5 seconds */  
                this.studentList = this.stnService.getStudents();  
                this.loading = false;  
            }, 5000);  
        }  
    }   


Step 7
You can seen I have created one variable loading this will decide whether loading spinner should show or not.
 
Before loading the data into variable I set as true .then the spinner will show.

    Then I given some time to show the spinner.
    After that I set to False to hide the spinner. As I mentioned no need of timer when API. Call.
    Once API call over set it as false.

Step 6

 
Let's create a Model dialog with the help of Bootstrap and call the data & spinner.
    <!-- Button to Open the Modal -->  
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">  
    Open modal  
    </button>  
    <!-- The Modal -->  
    <div class="modal" id="myModal">  
        <div class="modal-dialog">  
            <div class="modal-content">  
                <!-- Modal Header -->  
                <div class="modal-header">  
                    <h4 class="modal-title">popuploader</h4>  
                    <button type="button" class="close" data-dismiss="modal">×</button>  
                </div>  
                <!-- Modal body -->  
                <div class="modal-body">  
                    <div *ngIf="loading else loaded" class="loader"></div>  
                    <!-- Modal footer -->  
                    <div class="modal-footer">  
                        <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>  
                    </div>  
                </div>  
            </div>  
        </div>  
        <ng-template #loaded>  
            <p>student works!</p>  
            <table class="table">  
                <thead>  
                    <td>  
                         ID  
                      </td>  
                    <td>  
                         Name  
                      </td>  
                    <td>  
                      Marks  
                   </td>  
                </thead>  
                <tbody>  
                    <tr *ngFor="let std of studentList">  
                        <td>{{std.id}}</td>  
                        <td>{{std.name}}</td>  
                        <td>{{std.marks}}</td>  
                    </tr>  
                </tbody>  
            </table>  
        </ng-template>
 

In about code, we have created one button. That button will trigger the popup.
 
We should call the popup using the data-target attribute data-target="#myModal".
 
Mymodel is the id of model dialog.
 
In our process, I will load the spinner with the timer. In real-life cases, no timer is needed.
 
I have created ng template and I have loaded the data there.

    <ng-template #loaded>  
    …..  
    </ng-template> 
 

I gave the name of the template as loaded.
 
To show the templete I have set condition as,

    <div *ngIf="loading else loaded" class="loader">  
    </div>  

SO if loading variable is true then the loaded template will show with loader css.
 
If false then loader CSS will disappear
 
Now type ng serve to ( use angular CLI ) run the project.



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