Handling User-Agents in Node.js
Last Updated :
03 Jun, 2020
User-Agent is the information in the form of a string. This string lets the servers identify the type of application, operating system, version, and vendor of the incoming request from the Web-Browser. The common structure for the User-Agent will be-
User-Agent: product / product-version comment
Here, the name of the web browser from which the request is sent will be written in product. The version of the product will be written in product-version and, comment is optional. It contains more information on the product. For example, if the Web-Browser is Firefox, then user-agent will be-
Mozilla/5.0 (system-information)
platform (platform-details) extensions
The User-Agent module provides web browser properties. It also provides the data needed for blocking automated Browsers.
Setting up of User-Agent Module: To enable this module, first you need to initialize the application with package.json file and then install the user-agents module. So, let us firstly initialize our application with package.json file –
npm init
Now, install the module using –
npm install user-agents --save
To use this module in your application, simply write the following code –
const userAgent = require('user-agents');
Implementations: After installing the module, now let us look at some implementations of this module. The very basic implementation of this module is to generate random user agents. To generate a random user agent write the following code in the main.js file –
const UserAgent = require( 'user-agents' );
const userAgent = new UserAgent();
console.log(userAgent.toString());
|
Here, we are creating an instance of the User-Agent module with the help of new keyword. Then, we are logging the string format of the randomly generated user agent in the console. The output for the above code will be –
Mozilla/5.0 (Windows NT 10.0; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/80.0.3987.132 Safari/537.36
Further, if we want to print the data in JSON format, write the following code –
const UserAgent = require( 'user-agents' );
const userAgent = new UserAgent();
console.log(JSON.stringify(userAgent.data, null , 1));
|
Here, stringify() function will convert the JavaScript value into JSON. It takes three parameters, first one will be the value to be converted into JSON, the second parameter will be the replace function that will transform the result, and the third parameter will be for adding indentation, line-break characters so that the converted JSON string is easily readable.
The output for the above code will be –
{
"appName": "Netscape",
"connection": {
"downlink": 10,
"effectiveType": "4g",
"rtt": 100
},
"platform": "Win32",
"pluginsLength": 3,
"vendor": "Google Inc.",
"userAgent":
"Mozilla/5.0 (Windows NT 6.1; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/80.0.3987.132 Safari/537.36",
"viewportHeight": 790,
"viewportWidth": 1580,
"deviceCategory": "desktop",
"screenHeight": 900,
"screenWidth": 1600,
"weight": 0.00007295599223907504
}
This module also provides the functionality to restrict the application to be used in only specified devices. For example –
const UserAgent = require( 'user-agents' );
const userAgent = new UserAgent({ deviceCategory: 'mobile' })
|
Here, we have restricted our application to be used in only mobile devices. Instead of mobile, we can also write desktop or tablet.
Further, If you want to create multiple user agents with the same configuration or property, then write the following code –
const UserAgent = require( 'user-agents' );
const userAgent = new UserAgent({
platform: 'Win64' ,
deviceCategory: 'desktop'
});
const userAgents = Array(50).fill()
.map(() => userAgent());
|
Here, we have created an instance of a user agent with the properties as platform and deviceCategory. We are restricting it to use the Windows 64 platform and run only on desktop. Then, we created an array of 50 more user agents with the same configurations.
We can also apply a filter to our application and the returning user agent will be matched to the applied filter. Therefore, to apply a filter, write the following code –
const UserAgent = require( 'user-agents' );
const userAgent = new UserAgent(/Chrome/);
console.log(userAgent.toString());
|
Here, we are passing the filter as /Chrome/. The returning user agent will contain Chrome sub-string. We can also combine the filters and an array of configurations that are to be applied to the returning user agent.
For example –
const UserAgent = require( 'user-agents' );
const userAgent = new UserAgent([
/Chrome/,
{
deviceCategory: 'tablet' ,
platform: 'Win64'
}
]);
|
Here, we applied the filter as Chrome along with the array of configurations on the returning user agent.
Conclusion: In this article, we have learned about the User-Agent module of JavaScript and studied how to set up this module in a JavaScript file. We have also seen some of the implementations of this module.
Similar Reads
Handling Requests And Responses in Node.js
Node.js is a powerful JavaScript runtime for building server-side applications. It provides an efficient way to handle HTTP requests and responses using the built-in http module or frameworks like Express.js. Understanding HTTP Requests and ResponsesAn HTTP request is sent by a client (browser or AP
4 min read
Explain some Error Handling approaches in Node.js
Node.js is an open-source JavaScript runtime environment. It is often used on the server-side to build API for web and mobile applications. A large number of companies such as Netflix, Paypal, Uber, etc use Node.js. Prerequisites: PromisesAsync Await An error is any problem given out by the program
3 min read
How To Use An ES6 Import In Node.js?
To use an ES6 import in Node.js, you need to make some configurations to support ES6 modules. While Node.js was originally built around the CommonJS module system (require() and module.exports), modern JavaScript development prefers using the ES6 module syntax (import and export). Node.js now suppor
4 min read
What is Chaining in Node.js ?
Chaining in Node.js can be achieved using the async npm module. In order to install the async module, we need to run the following script in our directory: npm init npm i async There are two most commonly used methods for chaining functions provided by the async module: parallel(tasks, callback): Th
2 min read
Explain V8 engine in Node.js
The V8 engine is one of the core components of Node.js, and understanding its role and how it works can significantly improve your understanding of how Node.js executes JavaScript code. In this article, we will discuss the V8 engineâs importance and its working in the context of Node.js. What is a V
7 min read
How to Read Command Line Arguments in Node ?
Command-line arguments (CLI) consist of text strings utilized to provide extra information to a program during its execution via the command line interface of an operating system. Node facilitates the retrieval of these arguments through the global object, specifically the process object. ApproachTo
2 min read
How to use Class in Node ?
In Node, classes function as templates for creating objects in object-oriented programming, encapsulating both data and behavior. They provide a structured and reusable approach to defining and instantiating objects within a JavaScript program. We will discuss the following two approaches to define
3 min read
How to refresh a file in Node.js ?
Node.js has seen an important growth in past years and is still increasing its value in many organizations and business models. Companies like Walmart or PayPal have already started to adopt it. NPM, the package manager of Node.js has been already installed when you install Node.js and is ready to r
2 min read
How to Use Handle Get Request in Express.js ?
Express.js is a popular web application framework for Node.js, known for its simplicity and flexibility. One of the fundamental tasks in web development is handling HTTP requests, and GET requests are among the most common. This article will guide you through the process of handling GET requests in
3 min read
Node.js agent.createConnection() Method
The Node.js HTTP API is low-level so that it could support the HTTP applications. In order to access and use the HTTP server and client, we need to call them (by ârequire(âhttpâ)â). HTTP message headers are represented as JSON Format. The agent.createConnection() (Added in v0.11.4) method is an inbu
2 min read