NodeJS: Download File And Convert To Binary String

- 1 answer

I am pretty new to Node.js and struggle with current topic:

I am calling an API which returns me a file (audio.amr). I now need to convert this file during runtime, without saving it, to a binary string in order to pass it further.

I tried passing the received object to the "fs" module, but without any luck.

requestify.request('', {
                method: 'GET'
            }).then(function (response) { var obj = response.getBody() }

In "obj" is now a file returned that I need to convert to a binary string.



You can use an ArrayBuffer to hold binary data, then convert the ArrayBuffer to a Hex string. To get the raw body from requestify, you'll have to use the .body property instead of the getBody() function, according to their documentation.

You'll have to check what the raw body's type is and convert it to an ArrayBuffer if necessary.

// ...
var obj = response.body; // Get the raw body
var arrayBuffer = new TextEncoder().encode (obj); // Convert String data to ArrayBuffer (might need to be changed)
var hexString = bufferToHex (arrayBuffer);
// ...

function bufferToHex (buffer) {
    return Array
        .from (new Uint8Array (buffer))
        .map (b => b.toString (16).padStart (2, "0"))
        .join ("");


Since apparently requestify has no way to handle raw body data, I suggest you use node-fetch, a window.fetch polyfill for nodeJS.

Your code with it would look as follows:

const fetch = require ("node-fetch");

fetch(yourUrl, {
    method: 'GET'
}).then(function (response) { 
    return response.arrayBuffer ();
}).then(function (arrayBuf) {
    const hexString = bufferToHex (arrayBuf);
    // Do whatever you want