Home > Enterprise >  Use new File() on Nodejs
Use new File() on Nodejs

Time:10-05

I have to send static images to another Node app

To do this I need to get Base64 from file

This is the function I used in another project (VueJS web app):

export async function getBase64FromURL (path, filename) {
  const fr = new FileReader()
  fr.readAdDataURL(new File(path, filename))

  return await new Promise((resolve, reject) => {
    fr.onloadend = () => {
      resolve(fr.result)
    }
  })
}

NodeJS lacks some functions, for example FileReader() and I found this npm package

But I haven't found a solution for new File(), what can I do?

CodePudding user response:

// Import "fs" lib.
const fs = require('fs');

// Read file as buffer and convert to BASE64.
const fileBase64 = fs.readFileSync('./file.txt').toString('base64');
  • Related