2

I am requesting a rest server from nodejs by using nodejs request module.is it possible to determine the size of the data that will be returned to me (before accepting the data)?I want to cancel the operation if the size of the data that will be returned to me is more than the amount I determines.the purpose here is to ensure that my network is not locked.

My request part as follows;

const request = registry.get("requestPromiseNative");
const logger = registry.get("logger");
let env = registry.get("env");

 class SmartContractFetch {
constructor() {
this.dataSizeFetched = 0; //in bytes
}

async fetchData(method, url, data = {}, header = {}) {
try {
  logger.info("Smart contract fetch işlemi başladı.");
  if (method.toUpperCase() === "POST") {
    console.log("POS içinde  : " + JSON.stringify(data));
    let response = await request.post({
      url: url,
      resolveWithFullResponse: true,
      form: data,
      headers: header
    });
    let responseJSON = JSON.parse(response.body);
    this.dataSizeFetched += response.body.length;
    logger.info(
      "Smart contract fetch işlemi başarıyla tamamlandı. Gelen Data : " +
        responseJSON
    );
    return responseJSON;
  } else if (method.toUpperCase() === "GET") {
    console.log("GET içinde  : " + JSON.stringify(data));
    let response = await request.get({
      url: url,
      resolveWithFullResponse: true,
      form: data,
      headers: header
    });
    this.dataSizeFetched += response.body.length;
    let responseJSON = JSON.parse(response.body);
    logger.info(
      "Smart contract fetch işlemi başarıyla tamamlandı. Gelen Data : " +
        responseJSON
    );
    return responseJSON;
  }
} catch (error) {
  logger.error(
    "Smart contract fetch işlemi başarısız. Sonuç : " + error.message
  );
  throw new Error(error);
}
 }
 }
 module.exports = SmartContractFetch;
Baltazarr
  • 35
  • 1
  • 10
  • 1
    Possible duplicate of [How to limit response length with http.request in Node.js](https://stackoverflow.com/questions/15636095/how-to-limit-response-length-with-http-request-in-node-js) – Zak Feb 28 '19 at 13:18
  • Is there no way to understand the size of the data without bringing in the data. – Baltazarr Feb 28 '19 at 13:48
  • You can't guess the response size without reading it. The solution in the link, does not read all the data. It reads it as a stream, and stops at the limit. Do not worry about the network ressources. There will be no impact on that, if you set a low limit for the response size. Maybe there're other solutions, but I dont think you can do it only with Node. – Zak Feb 28 '19 at 13:57
  • Thank for reply.But I didn't coincide with the stream instance for all request types using nodejs http. I'm wrong. – Baltazarr Mar 01 '19 at 08:00
  • @Zak Thanks man.it solve my problem.And I want to upvote yur post if you could answer me below. – Baltazarr Mar 01 '19 at 13:40
  • It's ok, you're welcome – Zak Mar 01 '19 at 14:23

0 Answers0