Zlatan Omerovic
Zlatan Omerovic

Reputation: 4097

How to get response/body in text using node-libcurl?

I am using node-libcurl to communicate with my API which is supposed to return a plain JSON response. I am using the following code:

// cURL instance
const curl = new Curl();
const close = curl.close.bind(curl);

// cURL Options
curl.setOpt(Curl.option.URL, 'http://locally-hosted/consume.endpoint');
curl.setOpt(Curl.option.CONNECTTIMEOUT, 60);
curl.setOpt(Curl.option.FOLLOWLOCATION, true);
curl.setOpt(Curl.option.VERBOSE, true);

// Custom headers for this request
curl.setOpt(Curl.option.HTTPHEADER, [
    'Some: Value'
]);

// POST payload
curl.setOpt(Curl.option.POSTFIELDS, querystring.stringify({
    id: 1,
    value: 'foobar'
}));

// cURL cookie settings
const cookieJarFile = path.join(__dirname, 'cookiejar.txt');

curl.setOpt(Curl.option.COOKIEFILE, cookieJarFile);
curl.setOpt(Curl.option.COOKIEJAR, cookieJarFile);

// Cookie jar file check
if (!fs.existsSync(cookieJarFile)) {
  fs.writeFileSync(cookieJarFile);
}

// Event listener for data
curl.on('data', (chunk, curlInstance) => {
  console.log('Receiving data with size: ', chunk.length);
  console.log(chunk.toString());
});

// Event listener for end
curl.on('end', (statusCode, body, headers, curlInstance) => {
  console.info('Status Code: ', statusCode);
  console.info('Headers: ', headers);
  console.info('Body length: ', body.length);
  console.info('Body: ', body);

  curl.close();
});

// Error handler for cURL
curl.on('error', (error, errorCode) => {
  console.error('Error: ', error);
  console.error('Code: ', errorCode);
  curl.close();
});

// Commits this request to the URL
curl.perform();

I get the response in the data event listener or when the end event listener is complete. The problem which I'm facing is that I am getting the response in this representation:

Body:  �w[��x��%Yl��(|�q-�.
M$�kネ���A@\��eǽ�>B�E��
                         m�
                           -�

Which is, I figured a binary response, but I wasn't able to convert it in anything reasonable. Applying .toString() did not help, and, if you check data event listener, I said there: chunk.toString(), which returned me just the same thing.

How do I get a text body response using cURL for Node.js?

Upvotes: 0

Views: 1502

Answers (1)

Pranav Wani
Pranav Wani

Reputation: 53

Data received is passed as a Buffer to the end event, add this to your code.

curl.enable(CurlFeature.NoDataParsing);

For more informations please check the docs

Upvotes: -1

Related Questions