'Conversion of buffer data to blob in NodeJS

I get Buffer Data from a storage like <Buffer 48 65 79 20 74 68 65 72 65 21> for instance. I needed to convert it into a blob. But when i tried doing a toString() to get encoded text just like how a browser would render an attachment , i get all texts as unicode characters. I am in need of a blob I can send to UI along with other params in JSON , which could be used for view using HTML5 FileReader API. Could you please favour.

What i tried was below, where buffer refers to the data as in first line.

let binBuffer = Buffer.from(buffer,'binary').toString('utf8');


Solution 1:[1]

If you're here to convert a Node.js Buffer to a JavaScript Blob:

First of all, Node.js didn't have the Blob class until versions v15.7.0 and v14.18.0, so you need to import the Blob class if you haven't already:

// NOTE: starting from Node.js v18.0.0, the following code is not necessary anymore

// CJS style
const { Blob } = require("buffer");

// ESM style
import { Blob } from "buffer";

NOTE: it appears that in Node.js v14/v15/v16/v17 (last checked: as of v14.19.2, v15.14.0, v16.14.2 and v17.9.0), the Blob class is marked as experimental and not stable. Instead, in Node.js v18.x.x the Blob class is marked as stable.

UPDATE 2022-04-25: starting with Node.js version 18.0.0, you don't have to manually import the Blob class anymore, but you can use it straight away in your code!

Once the Blob class is available, the conversion itself is pretty simple:

const buff = Buffer.from([1, 2, 3]); // Node.js Buffer
const blob = new Blob([buff]); // JavaScript Blob

Old answer about how to transfer a Node.js Buffer via JSON:

If you need to transfer a buffer of data through JSON, you can encode the buffer using a text-based encoding like hexadecimal or base64.

For instance:

// get the buffer from somewhere
const buff = fs.readFileSync("./test.bin");
// create a JSON string that contains the data in the property "blob"
const json = JSON.stringify({ blob: buff.toString("base64") });

// on another computer:
// retrieve the JSON string somehow
const json = getJsonString();
const parsed = JSON.parse(json);
// retrieve the original buffer of data
const buff = Buffer.from(parsed.blob, "base64");

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1