5

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.

5
  • This will help you: https://stackoverflow.com/questions/14653349/node-js-can%C2%B4t-create-blobs Commented Jun 27, 2020 at 9: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. Commented Jun 27, 2020 at 10:20
  • const Blob = require("cross-blob"); Doesn't fit your needs? Commented Jun 27, 2020 at 10:32
  • Did you get a solution Commented Jun 25, 2021 at 4: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 Commented Jun 25, 2021 at 6:29

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
1

Node 19.8 has a new API for this: fs.openAsBlob(path, options)

See https://github.com/nodejs/node/issues/45188#issuecomment-1475017344

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.