Make Synchronous HTTP Request in Node.js

04/10/2023

Contents

In this article, you will learn how to make synchronous HTTP request in Node.js.

Making synchronous HTTP request in Node.js

In Node.js, you can make synchronous HTTP requests using the built-in http module. By default, Node.js uses asynchronous I/O operations, but sometimes you may need to perform a synchronous HTTP request in your code.

Here’s an example of how to make a synchronous HTTP GET request in Node.js:

const http = require('http');

const options = {
  hostname: 'www.example.com',
  port: 80,
  path: '/some/path',
  method: 'GET'
};

const req = http.request(options);
req.end();

const res = req.on('response', function(response) {
  const responseData = [];
  response.on('data', function(chunk) {
    responseData.push(chunk);
  });

  response.on('end', function() {
    const finalData = Buffer.concat(responseData);
    console.log(finalData.toString());
  });
});

console.log('Request complete.');

In this example, we first require the built-in http module. We then define an options object that specifies the hostname, port, path, and HTTP method for the request. We create a new HTTP request using http.request(options) and call req.end() to send the request.

We then listen for the response event on the request object, which fires when the server responds to the request. In the response event listener, we create an array to store the chunks of data returned by the server, and append each chunk to the array using the push() method. When the response ends, we concatenate the chunks into a single buffer using Buffer.concat(), convert the buffer to a string using toString(), and log the response data to the console.

Finally, we log a message indicating that the request is complete.

Note that making synchronous HTTP requests in Node.js is generally not recommended, as it can block the event loop and cause performance issues. If possible, it’s better to use asynchronous HTTP requests with callbacks or promises.