NodeJS: Download File And Convert To Binary String
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('https://some-url.com', {
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.
Answer
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 ("");
}
Update:
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
});
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM