3

I am trying to write a function that returns me a Blob or File object, blob_object, while taking in the local filepath of an object, tmpFilePath, and I have to use NodeJS to do it as the function is used as part of a Firebase cloud function. I have tried many methods, but none of them work. They mainly revolve around this.

Attempt 1: Using streamToBlob. Inspired from reddit

const streamToBlob = require('stream-to-blob');
const fs = require('fs-extra');


const input_read_stream = fs.createReadStream(tmpFilePath);
const blob_object = await streamToBlob(input_read_stream);

Error: ReferenceError: Blob is not defined

Attempt 2: using blob. Inspired from stackoverflow

const Blob = require('blob');
const fs = require('fs-extra');

const file_buffer = fs.readFileSync(tmpFilePath);
const blob_object = new Blob([file_buffer]);

Error: TypeError: Blob is not a constructor.

A workable solution would mean that upon writing code in my file, file.js, I would be able to run node file.js and console.log a Blob or File object. Does anyone know how this can be done in a series of steps? I'm on Node 8.

Prashin Jeevaganth
  • 1,223
  • 1
  • 18
  • 42
  • This will help you: [https://stackoverflow.com/questions/14653349/node-js-can%C2%B4t-create-blobs](https://stackoverflow.com/questions/14653349/node-js-can%C2%B4t-create-blobs) – Kai Lehmann Jun 27 '20 at 09:49
  • @KaiLehmann I also saw that post earlier too, but did not understand how the solutions given will solve my problem. They are either working with client side code or doing it via requests. – Prashin Jeevaganth Jun 27 '20 at 10:20
  • const Blob = require("cross-blob"); Doesn't fit your needs? – Kai Lehmann Jun 27 '20 at 10:32
  • Did you get a solution – Sayan Dey Jun 25 '21 at 04:36
  • @SayanDey I still faced this problem when trying out the solution. However, I realised my client has a slightly different requirement so this situation could be avoided creating files from the node side – Prashin Jeevaganth Jun 25 '21 at 06:29

1 Answers1

4

As of writing, Blob support is still experimental, but this should work in recent versions of Node.js:

import fs from "fs";
import { Blob } from "buffer";

let buffer = fs.readFileSync("./your_file_name");
let blob = new Blob([buffer]);

So your second example should work if you upgrade Node to v16.

joe
  • 3,752
  • 1
  • 32
  • 41
  • This saved me. I lost 4 days trying to have a PersistenFile instance (from formidable package) appended to a FormData and sending it as a fetch api request. Buffer + Blob solved it. – Bruno Lamps Jan 08 '23 at 20:38