NodeJS convert base64 to octet-stream

I’m trying to access one API which received octet-stream as parameter. For that I wanted to convert base64 string to octet-stream first. In javascript I have achieved it using the default Blob type. But in NodeJS I am not able to make it to perfect format which would be consumed by the API.

I have tried to convert it to Buffer and ArrayBuffers also, but no use. I have also tried cross-blob library, but still it is not being converted to the exact format as I was getting in javaScript.

Answer

Try this :

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


let subscriptionKey = '<your key here>';
let endpoint = '<endpoint url of your vision serice>';
let filePath = '<path of your file>';

//code below is what you are looking for 
const base64 =  fs.readFileSync(filePath, 'base64') 
const data = Buffer.from(base64, 'base64')

if (!subscriptionKey) { throw new Error('Set your environment variables for your subscription key and endpoint.'); }

var uriBase = endpoint + "vision/v2.1/ocr";  //you define your API here , in this case I use ocr 

fetch(uriBase + "?" + {
    "language": "unk",
    "detectOrientation": "true",
},
{
method: 'POST',
headers: 
    {
    'Content-Type': 'application/octet-stream',
    'Ocp-Apim-Subscription-Key': subscriptionKey,
    },
body: data,    //post binary data directly, it applys to all post methods which data type is octet-stream in vision serice API 
}).then((response) => response.json()).then((data) =>
{
console.log(JSON.stringify(data, null, 2));
}).catch((error) =>
{
console.log(error);
});

Result :

enter image description here

Hope it helps.