Prashin Jeevaganth
Prashin Jeevaganth

Reputation: 1363

Return a File object from a local filepath in NodeJS

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.

Upvotes: 5

Views: 13337

Answers (2)

joe
joe

Reputation: 5662

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.

Upvotes: 6

Related Questions