NodeJS - Substituting HTTPS get request with fetch

Viewed 51

One of the NodeJS external libraries I am using has the following code:

const HTTPS = require('https');

exports.getPage = (ref, cb) => {
  const request = HTTPS.get(ref, resp => { // eslint-disable-line consistent-return
    if (resp.statusCode !== 200) return cb(new Error(`Status Code ${resp.statusCode}`));
    const respBuffer = [];
    resp.on('data', d => respBuffer.push(d));
    resp.on('end', () => {
      cb(null, Buffer.concat(respBuffer).toString());
    });
  });
  request.on('error', cb);
};

I am trying to imitate that same request in my React Native code. However, I am not sure what exactly is the format of the respBuffer and what Buffer.concat does to it.

I have been trying to replicate the output data of the function above with this code, however, unsuccessful:

export const getPage = (ref, cb) => {
    fetch(ref)
    .then((response) => response.json())
    .then((resp) => {
        cb(null, resp);
    })
    .catch((err) => "Error:", cb)
};

I would appreciate any help or advice!

0 Answers
Related