Full Trust European Hosting

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

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

clock May 30, 2022 08:55 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')
  }
})


Summary
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 Europe - HostForLIFE :: Create a Redis Cache with Express Node JS

clock May 11, 2022 09:02 by author Peter

This article provides a sample application using the Redis Cache with explanation. Please see this article on how to create an Express Node JS application, so that we can quickly jump into the topic without further delay.

Why is Caching required?
When the same response needs to be served multiple times, store the data in distributed server memory as and it can be retrieved faster than the data retrieved from the storage layer for every single call. Caching is an ability of an application to duplicate the values for a specified period of time and serve the web request instantly.

These techniques will be effective when
    There is a need to call for a 3rd party API and the call counts
    Cost of data transfer between cloud and the server.
    Server response is critical based on the concurrent requests.

What is Redis Cache?
The data cache stored in a centralized distributed system such as Redis. Redis is also called a data structures server, which means a variety of processes can query and modify the data at the same time without much loading time.
Advantages of Redis

The special properties of data structures are

    Even though the data is often requested, served and modified, the data will be stored in disk rather than storing in RAM.
    Unlike high-level programming language, the implementation will highlight on memory optimal usage.
    Also offers features like replication, levels of durability, clustering and high availability (HA).
    Redis can handled complexed Memcached operations like Lists, Sets, ordered data set, etc.,

Using Redis Client in local system

To use the Redis, you need to install Node JS Redis Client in the local system. The msi file (v3.0.504 stable version as of this article published date) can be downloaded from the Github and proceed with normal installation process (for Windows OS).

The latest Redis Client can be also be installed with Windows Subsystem for Linux (WSL) and install the Redis 6.x versions. Also, for dockerizing, Mac and Linux OS’ follow the instructions on downloads

Run the Redis Client by the following command

redis-server

Create an Express Node JS application

Open the PowerShell or cmd prompt window and go to the destined folder.

Execute the following command
npx express expressRedisCaching –hbs

Install the modules using the command
npm i

and install the following additional packages
npm i redis
npm i isomorphic-fetch


Once all the packages are installed and ready to start. I have created a new route page called “getCached.js” and mapped in the “App.js” page.
app.use('/getCached', require('./routes/getCached'));

Upon calling the endpoint, the logic is to fetch the response from JSON placeholder (mock API) site, store the data in Redis Cache and respond to the request. On further request, cached data will be served.
const express = require('express')
require('isomorphic-fetch')
const redis = require('redis')
const router = express.Router()
const client = redis.createClient({
    host:'127.0.0.1',
    port:6379
})



router.get('/',async(req, res)=>{

        await client.connect();
        const value = await client.get('todos');
        if(value){

            console.log("from cached data")
            res.send(JSON.parse(value))
        }
        else{

            const resp = await fetch(sourceURL)
               .then((response) => response.json());
            await client.set('todos', JSON.stringify(resp));
            console.log("from source data")
            res.send(resp);
        }
        await client.disconnect();

})

module.exports = router

Object created using the redis is
redis.createClient({ host:’127.0.0.1’, port:6379});

With options
    host : currently the Redis is available in the local system and so the host is default 127.0.0.1
    port : by default Windows OS is allocating 6379 port to Redis, but the same can be customized.

Now it’s time to run the app by executing the command
npm start

 

On the first hit, the data is fetched from the source API with the response time of approximately 1156ms and the same has been stored in the in-memory data store Redis Cache. The second hit gets the data from the cached with the remarkable reduction in fetch time of just ~10 ms or even ~6ms.

Thus, the objective is met with very few easy steps.



Node.js Hosting Europe - HostForLIFE :: How To Make Middleware In Node.js

clock April 13, 2022 09:13 by author Peter

Node.js is a backend framework based on Javascript. It is said to be 10x faster as compared to other backend languages as it is developed keeping in mind Javascript runtime browser compatibility.


Node.js uses non-blocking I/O, the main reason for making it lightweight and efficient.

Moreover, it is open-source, cross-platform runtime environment for developing server-side applications.

Some other backend languages,
    PYTHON.
    PHP LARVEL.
    GOLANG.
    C#.
    RUBY.
    JAVA.

But the fact is node.js is said to be fastest among all as it totally works on npm (node package manager) which gives developers multiple tools and modules to use thus helping in execution of code in the fastest way as possible.
Requirements

Starting with nodejs is an easy task just by downloading/installing it, if not yet downloaded, here’s the link to download.

After installing node.js on your  local computer or laptop, to check node gets properly installed on a particular system, open command prompt and type node -v to check.

There you go😊. Creating Middleware using Express Apps - Overview

Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. The next function is in the Express router which, when invoked, executes the middleware succeeding the current middleware.

The following task can be performed through middleware,
    Execute any code.
    Make changes to the request and the response objects.
    End the request-response cycle.
    Call the next middleware in the stack.

If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

The following figure shows the elements of a middleware function call,

HTTP method.
Path (route) for which the middleware function applies
The middleware function.
Callback argument to the middleware function.
HTTP response argument to the middleware.
HTTP request argument to the middleware

Starting with Express 5, middleware functions that return a Promise will call next(value) when they reject or throw an error.

next will be called with either the rejected value or the thrown Error.

Example
Here is an example of a simple “Hello World” Express application. The use of this article will define and add three middleware functions to the application: one called myLogger that prints a simple log message, one called requestTime that displays the timestamp of the HTTP request, and one called validateCookies that validates incoming cookies.
const express = require('express')
const app = express()
app.get('/', (req, res) => {
    res.send('Hello World!')
})
app.listen(3000)


Middleware function myLogger
Here is a simple example of a middleware function called “myLogger”. This function just prints “LOGGED” when a request to the app passes through it. The middleware function is assigned to a variable named myLogger.
const myLogger = function(req, res, next) {
    console.log('LOGGED')
    next()
}


Notice the call above to next(). Calling this function invokes the next middleware function in the app. The next() function is not a part of the Node.js or Express API but is the third argument that is passed to the middleware function. The next() function could be named anything, but by convention it is always named “next”. To avoid confusion, always use this convention.

To load the middleware function, call app.use(), specifying the middleware function. For example, the following code loads the myLogger middleware function before the route to the root path (/).
const express = require('express')
const app = express()
const myLogger = function(req, res, next) {
    console.log('LOGGED')
    next()
}
app.use(myLogger)
app.get('/', (req, res) => {
    res.send('Hello World!')
})
app.listen(3000)


Every time the app receives a request, it prints the message “LOGGED” to the terminal.

The order of middleware loading is important: middleware functions that are loaded first are also executed first.

If myLogger is loaded after the route to the root path, the request never reaches it and the app doesn’t print “LOGGED”, because the route handler of the root path terminates the request-response cycle.

The middleware function myLogger simply prints a message, then passes on the request to the next middleware function in the stack by calling the next() function.

Middleware function requestTime

Next, we’ll create a middleware function called “requestTime” and add a property called requestTime to the request object.
const requestTime = function(req, res, next) {
    req.requestTime = Date.now()
    next()
}


The app now uses the requestTime middleware function. Also, the callback function of the root path route uses the property that the middleware function adds to req (the request object).
const express = require('express')
const app = express()
const requestTime = function(req, res, next) {
    req.requestTime = Date.now()
    next()
}
app.use(requestTime)
app.get('/', (req, res) => {
    let responseText = 'Hello World!<br>'
    responseText += `<small>Requested at: ${req.requestTime}</small>`
    res.send(responseText)
})
app.listen(3000)


When you make a request to the root of the app, the app now displays the timestamp of your request in the browser.
Middleware function validateCookies

Finally, we’ll create a middleware function that validates incoming cookies and sends a 400 response if cookies are invalid.

Here’s an example function that validates cookies with an external async service.
async function cookieValidator(cookies) {
    try {
        await externallyValidateCookie(cookies.testCookie)
    } catch {
        throw new Error('Invalid cookies')
    }
}


Here we use the cookie-parser middleware to parse incoming cookies off the req object and pass them to our cookieValidator function. The validateCookies middleware returns a Promise that upon rejection will automatically trigger our error handler.
const express = require('express')
const cookieParser = require('cookie-parser')
const cookieValidator = require('./cookieValidator')
const app = express()
async function validateCookies(req, res, next) {
    await cookieValidator(req.cookies)
    next()
}
app.use(cookieParser())
app.use(validateCookies)
// error handler
app.use((err, req, res, next) => {
    res.status(400).send(err.message)
})
app.listen(3000)


Note how next() is called after await cookieValidator(req.cookies). This ensures that if cookieValidator resolves, the next middleware in the stack will get called. If you pass anything to the next() function (except the string 'route' or 'router'), Express regards the current request as being an error and will skip any remaining non-error handling routing and middleware functions.

Because you have access to the request object, the response object, the next middleware function in the stack, and the whole Node.js API, the possibilities with middleware functions are endless.

Configurable middleware

If you need your middleware to be configurable, export a function that accepts an options object or other parameters, which, then returns the middleware implementation based on the input parameters.

File: my-middleware.js
module.exports = function(options) {
    return function(req, res, next) {
        // Implement the middleware function based on the options object
        next()
    }
}
// The middleware can now be used as shown below.
const mw = require('./my-middleware.js')
app.use(mw({
    option1: '1',
    option2: '2'
}))


Summary
Depending on our short definition, middleware can be created for purposes such as database transactions, transactions between application servers, message controls, and authentication. Structures such as soap, rest, and JSON can be used in the communication of applications. The middleware acts according to all these purposes.



Node.js Hosting Europe - HostForLIFE :: How To Work With File System Module In Node.js

clock March 11, 2022 07:52 by author Peter

Node file system helps us to access the files and also interact with files in our system. Node.js’s file system module is also known as "fs" module. We don’t need to install it explicitly as it comes with Node.js core. We can use the fs module as
var fs = require('fs');

File system module can be used for file operations like creating, reading, deleting, etc. The operations that we need to perform can have synchronous and asynchronous forms depending on our requirements.

Common use cases of File System module:
    Write Files
    Read Files
    Delete Files
    Append Files
    Close Files

Read File
To read the file from our system, fs.ReadFile() function is used. fs.readFile() is a built-in function used to read files located in our system with the syntax given below

Syntax
fs.readFile( filename, encoding, callback_function )

In the parameters, we can provide a filename as the name of the file if it is located in the same directory and a full path if the file is located on locations other than the same directory. Encoding has the encoding value of the file, by default the value of encoding is utf8.

The callback function is the function that is called once the file is read. This function takes two parameters first is err and the other is data. Err indicates if any error has occurred during reading the file and data contains the content of the file.

To create a demo for this function let's create a text file. Create a text file named “FirstFile.txt” with “My First File.” as content.

Now let's create a file named “FileRead.js”, to read the contents of the text file that we created.

Example
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
  fs.readFile('FirstFile.txt', "utf-8" , function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);
console.log("File Read!");


Note
If the output is undefined it means the file is null. It starts reading the file and simultaneously executes the code. The function will be called once the file has been read meanwhile the ‘File Read!” statement is printed then the contents of the file are printed.

Initiate the file
node .\FileRead.js

Opening the localhost, we will be able to read the contents of the file as shown below,

Create File
Creating files using node.js can be done through many approaches. Some of the methods that can be used are appendFile(), open(), or  writeFile(). Let’s look into the details of each function and when to use it.
fs.appendFile()

The fs.appendFile() method of Node.js is used to synchronously append the data to the file, if the file doesn’t exist then a new file will be created with the content specified.

Syntax
fs.appendFile(filepath, data, options, callback);

In the parameters, filepath will be the path of the file provided as a string, parameter data is the data that we need to append to the file, options specifies the flag/encoding/mode and the callback is a function that is called when the data is appended to the file.

Example
var fs = require('fs');
fs.appendFile('AppendFile.txt', 'Append File demo!', function (err) {
  if (err) throw err;
  console.log('Content appended/file created.');
});


Initiate the file:

A new file named 'AppendFile.txt' will be created if it doesn’t exist and if the file exists the text provided in the code will be appended.
fs.open()

The fs.open() method is used to create, read, or write a file. Writing to a file using open() method depends on the second parameter flag, passed to the method. If we pass the parameter as “w” then the specified file is opened for writing. If the file doesn’t exist then a new blank file is created with the name specified.

Syntax
fs.open(path, flags, mode, callback)

The parameters path holds the name of the file if the file is located in the same directory and it contains the entire path if the file is located at other locations.

Mode sets the mode of the file for example r-read, w-write, r+ -readwrite, etc. The default value of the mode is readwrite.

The parameter flag indicates the behavior of the file to be opened. The values that we can provide for the value of flag parameter are r, r+, rs, rs+, w, wx, w+, wx+, a, ax, a+ or ax+.

The callback function is the function that is called after reading the file.

Let’s try to create a blank file using the open method of the fs module of Node.js.
var fs = require('fs');
fs.open('OpenFile.txt', 'w', function (err, file) {
  if (err) throw err;
  console.log('New file created!');
});


Initiate the file,

The fs.readFile() method is used only for reading the file and fs.writeFile() method is only for writing to the file, whereas fs.open() method does several operations on a file such as creating, reading, or writing.
fs.writeFile()

The method WriteFile() replaces the specified file and content if the file already exists. If the file doesn’t exist, then a new file will be created with the content as provided. This method is used to asynchronously write the specified data to a file.

Syntax
fs.writeFile(path, data, options, callback)

The path parameter here can be a string, Buffer, URL, or file description integer that denotes the path of the file where it has to be written. Using a file descriptor will make it behave similarly to fs.write() method.

Example
var fs = require('fs');
fs.writeFile('WriteFile.txt', 'New file created with content!', function (err) {
  if (err) throw err;
  console.log('File created and saved!');
});


Initiate the file,

Update Files
To update the files there are some methods from the file system module that can be used.
Methods that can be used for updating the files are fs.appendFile() and fs.writeFile().

As we already have the description of the function fs.appendFile() in the create file section, let’s have a look at an example.
var fs = require('fs');
fs.appendFile('AppendFile.txt', ' Appended text...', function (err) {
  if (err) throw err;
  console.log('Updated!');
});


Initiating this file will append the data to the existing file.

For details of the fs.writeFile() function please refer to create file section. Looking at an example of fs.writeFile() function:
var fs = require('fs');
fs.writeFile('WriteFile.txt', 'File with name WriteFile updated.', function (err) {
  if (err) throw err;
  console.log('File updated and saved!');
});


Initiating the file replaces the specified file and the contents will be updated and the file will be saved.

Delete Files
To delete files using Node.js, we can use the method fs.unlink(). This function is used to remove a file, it doesn’t work on deleting directories. To delete directories we can use the method fs.rmdir().

Syntax
fs.unlink(path, callback)

Here in this method we need to pass two parameters first is the path of the file that we need to remove, it can be string, Buffer, or URL. And another parameter is the callback. The callback is a function that would be called when the method is executed.

Example
var fs = require('fs');
fs.unlink('SampleFile.txt', function (err) {
  if (err) throw err;
  console.log('SampleFile deleted...');
});


Initiating the file, the file that we mentioned in the code will be deleted.

Rename Files
We can also rename the file names using Node.js and to rename the file names we can use the function fs.rename(). The function will be used to rename the file at oldPath to the pathname provided as newPath.

The parameters used to rename the file are oldpath, newpath, and the callback function. Here old path will be the path of the file that already exists, a new path will be the new name of the file that we want to replace the old file name with. And the callback function will be the function that will be called when the method is executed.

In the case that newPath already exists, it will be overwritten. If there is a directory at newPath, an error will be raised instead. No arguments other than a possible exception are given to the completion callback.

Example
var fs = require('fs');
fs.rename('SampleFile.txt', 'SampleFileRenamed.txt', function (err) {
  if (err) throw err;
  console.log('SampleFile File Renamed!');
});

Initiating the file, the old file will be replaced with the new file name provided.

After going through this article and performing the code snippets provided you will be able to work with all the basic file operations such as create, update, delete and rename. Please feel free to post the feedback if any and let me know if you want me to work on any content that would help to learn Node.js further.



Node.js Hosting - HostForLIFE :: Invoke REST APIs In Express JS

clock October 5, 2021 07:03 by author Peter

This article will explain the steps involved in invoking APIs from the Express JS framework. The code below will assume the REST APIs are already developed and available for consumption.

Create a simple Express application
Use the below lines of code to create an Express app.

const express =require(‘express’);
const app = express();
app.get('/', function (req, res) {
  res.send('Hello World!')
})
app.listen(3000);

The app will respond with a Hello World message when a GET request is initiated (http://localhost:3000)

Invoke REST APIs

GET method,

const request = require('request');
//define http request implementation in a separate file to handle request input and output //parameters
async function getEmployee(req, res) {
    let body = req.body;
    let options = {
        hostname: ‘http: //sampleservice.com/’,
            path: '/api/Employee'
        method: ‘GET’
    }
    let result = await request(options);
    res.send(); // or return specific parameter value in JSON format
}


Invoke POST method,
async function UpdateEmployee(req, res) {
    let body = req.body;
    let details = {
        name: body.name,
        id: body.id,
        title: body.title
    };
    let options = {
        hostname: http: //sampleservice.com/,
            path: '/api/employee?' + new params({
                name,
                id,
                title
            }),
        method: 'POST'
    }
    let result = await request(options, details);
    res.json({
        body.id,
        body.name,
        body.title
    });
}


API calls also can be made using fetch command with minimal code, it requires at least Node.js 12.20 version.



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



Node.js Hosting - HostForLIFE.eu :: 10 Reasons Why "Node.js" Is A First Choice For Web-App Development

clock December 4, 2020 09:00 by author Peter

Node.js was created by Rayn Dahl in 2009 and his work was supported by Joyent. The core idea behind its development was extending Javascript into something that can not only run in the browser but also operate on the machine as a standalone application.
 
What can Node.JS do? Can you use it to build your first highly-secured application?
 
If you are asking these questions, then you are in the right place. Today, we are going to inform you why there’s so much hype among the developers when it comes to Node.js.
 
With so many technologies for development, it can be tough to choose the one which you can easily master yet it can give you better results. Besides, as a beginner, it’s way tougher to choose. So why should you go for Node.js? What makes it so special? Let’s get started from the basics.
 
Node.js was created by Rayn Dahl in 2009 and his work was supported by Joyent. The core idea behind its development was extending Javascript into something that can not only run in the browser but also operates on the machine as a standalone application.
 
Along with Javascript, Node.js runs on the specific Javascript runtime engine, i.e., V8. This runtime engine takes your code from Javascript and transforms it into rapid machine code.
 
Besides, several top-notch apps like Uber, PayPal, Netflix, etc. state that Node.js has powered their web applications and has provided a much faster interface.
 
Why Node.js?
 
Node.js is a Javascript runtime environment that promotes open-source and cross-platform functionalities. It helps in the execution of Javascript outside a browser. With the help of Node.js, one can create a dynamic web application or web page by writing and running a command-line for server-side scripting before the page is being shared at the user’s end.
 
It provides a unique blend of helpers, libraries, and other tools that make the web app development process efficient, easier, and simpler to operate. Besides, it offers a powerful base to develop web apps while securing an online presence.
 
Node.js uses a non-blocking, event-driven I/O Model that turns it light and efficient. It has one of the largest open-source libraries ecosystems, NPM. Besides, it uses push technology on web sockets that allows 2-way communication between server and client. One of the perfect examples of this feature of Node.js is Chatbots. You might have come across one of those while visiting a website’s customer service as well.
 
So now that you have a clear understanding of what you can do with Node.js, let’s get to the details that make it astounding!
 
Reasons that Make Node.js Exceptional!
 
Fast & Scalable
The scalability that Node.js provides to an organization has boosted their profits. As we have already discussed that Node.js runs on V8, its speed in terms of computing is unbeatable. With the new JS code conversion into the native language, the outcoming speed of operation has inspired several large and small institutions.
Besides, Node.js can help you with its ability to run a large batch of asynchronous processes simultaneously. Unlike other technologies for development, Node.js can complete reading, writing, or modifying a database in a shorter timeline.
 
Supremely Extensible
Another vital feature of Node.js is its extensibility. According to the requirements you have, the capabilities it has can be constructed and extended. For any developer who wants to share data among the web server and client, Node.js is there for your aid. It saves the coder from modulating differences in syntax while writing for the backend.
 
Easy To Learn & Code
From the very beginning, Javascript has been introduced in the coding world. It has improved and evolved itself with the internet. That means, almost every programmer or developer has a little bit of Javascript knowledge. But for those who don’t know what the heck is Javascript, it’s the basic and simple language that anyone can efficiently learn in minimum time.
 
As the V8 engine is created for JS coding and deployment by Google Chrome, it makes your work problem-free, and easy. So to get fabulous deployment results, all you need to do is code with JS along with Node.js and your stunning web-app is on its way!
 
Enhanced Productivity
Being entirely based on Javascript, Node.js removes the requirement for having different developers. Be it front-end or back-end, you can easily do it with Node.js instead of relying on other programming languages to complete the task which in return increases productivity.
 
Pervasive Runtime
With the arrival of Node.js, Javascript has been freed from the limitation of the environment as well. Now you can use JS on the client-side along with the server-side.
 
Regardless of where you are manipulating with the files, the effects can easily be seen on the other side.
 
Data Streaming
When it comes to Data Streaming, Node.js can effectively handle both input and output requests to support the online streaming functionality. It uses data streams to run certain operations at the same time it processes data.
 
Single Codebase
As you can write code in JS on both server and client-side, Node.js makes code execution and deployment faster and easier. Moreover, as language conversion is not required in Node.js, the data can be easily transferred from client to server and vice-versa.
 
NPM
NPM or Node.js Package Module enables different environmental packages to indulge into the existing one. It makes the development and performance robust, consistent, and quicker. There are more than 6000 modules available in Node.js that competes with ruby and will soon surpass it.
 
Database Query Resolutions
With Node.js working for both front-end and back-end, there is no need for you to worry about the translation of codes which also promotes flawless streaming while easily solving the database queries by itself.
 
Proxy Server
Node.js acts like a proxy server that gathers data resources and gives the third-party app enough time to perform the requested/required actions.
 
Conclusion
Node.js comes with plenty of benefits which makes it an adequate choice for developing a web application. While using it in your next project, you can not only assure less turnaround time, but also ensure an amazing output level.
 
If you want to empower yourself as a developer and you want the user of your web application to utilize the application to its highest extent in order to yield desirable outcomes, then Node.js is an ideal alternative.
 
Overall, it would not be wrong to say that Node.js has become the first choice for web app developers. There are several reasons Node.js has flourished so much and will undoubtedly reach great heights in the application development industry. It gives you what you want so you can offer creative solutions.



Node.js Hosting - HostForLIFE.eu :: Uploading File in Node.js

clock November 18, 2020 07:38 by author Peter

In this article we will observe uploading a file on a web server made use Node.js. Stream in Node.js makes this task super simple to upload files or so far as that is concerned working with any information exchange between a server and a client. To transfer a file we will work with two modules, HTTP and fs. So let us begin with stacking these two modules in an application:

var http = require('http');
var fs = require('fs')


When modules are loaded proceed to and make a web server as below:
http.createServer(function(request,response){   
  }).listen(8080);


So far we are great and now we wish to utilize the accompanying procedure:
Make a destination write stream. In this stream the substance of the uploaded file will be written. We need to compose once again to the client the rate of data being uploaded.

The first requirement could be possible utilizing a pipe. A pipe is an event of stream in Node.js. And the request is a readable stream. So we will use a pipe event to write a request to a readable stream.
var destinationFile = fs.createWriteStream("destination.md");     
      request.pipe(destinationFile);


The second necessity is to give back an of data uploaded. To do that first read the aggregate size of the file being uploaded. That could be possible by reading the content-length (line number 1 in the accompanying code snippet). At that point in the data occasion of request we will update uploadedBytes that starts at zero (line number 2). In the data event of the request we are calculating the percentage and writing it back in the response.

Now, It’s time to putting it all together your app should contain the following code to upload a file and return the percentage uploaded.
var http = require('http');
var fs = require('fs');
  http.createServer(function(request,response){    
    response.writeHead(200);
      var destinationFile = fs.createWriteStream("destination.md");      
      request.pipe(destinationFile);
      var fileSize = request.headers['content-length'];
      var uploadedBytes = 0 ;
      request.on('data',function(d){  
          uploadedBytes += d.length;
          var p = (uploadedBytes/fileSize) * 100;
          response.write("Uploading " + parseInt(p)+ " %\n");
     });
      request.on('end',function(){
            response.end("File Upload Complete");
          });
    }).listen(8080,function(){        
        console.log("server started");
         });

On a command prompt start the server as in the picture below:

Presently let us utilize curl -upload-file to upload a file on the server.

As you see, while the file is being uploaded the percentage of data uploaded is returned once again to the client. So thusly you can upload a file to the server made utilizing Node.js. Hope this tutorial works for you!



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