Express.js – req.range() Method


req.range() is basically a range header parser. The accept-ranges and the response-header fields allow the server to indicate the acceptance of the range requests from a resource.

Syntax

req.range( size, [options])

Parameters

The above parameters are defined as follows −

  • size – The size parameter defines the maximum size of the resource.

  • options – The options parameter can have the following properties −

    • combine – It is a Boolean type variable. This parameter specifies if overlapping and whether the adjacent ranges should be combined or not. Default: False

Example 1

Create a file with the name "reqRange.js" and copy the following code snippet. After creating the file, use the command "node reqRange.js" to run this code as shown in the example below −

// Specifying status code Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();
var PORT = 3000;

// Creating an endpoint
app.get("/api", (req, res) => {
   res.status(400);
   res.send("Bad Request Received")
})

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Hit the following URL endpoint for a GET request −

http://localhost:3000/

and set the following property in header −

--> Range(Key) -> bytes=500-1000

Output

C:\home
ode>> node reqRange.js Server listening on PORT 3000 bytes=500-1000 [ { start: 500, end: 1000 }, type: 'bytes' ]

Example 2 Without Range header set

Let's take a look at one more example.

// req.range() code Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();
var PORT = 3000;

// Creating an endpoint
app.get('/', function (req, res) {
   console.log(req.range());
   res.end();
});

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Hit the following URL endpoint for a GET request − http://localhost:3000/

Output

C:\home
ode>> node reqRange.js Server listening on PORT 3000 undefined

Updated on: 28-Mar-2022

441 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements