Home > Software design >  Converting Base64 stream to file object without saving
Converting Base64 stream to file object without saving

Time:02-18

In Node.js, I want to use a Base64Stream from one module and use it as a file in another.

I am getting email attachments from mail-listener2 which return like this:

{
  contentType: 'image/png',
  contentDisposition: 'attachment',
  transferEncoding: 'base64',
  generatedFileName: 'attachment.png',
  contentId: '4b07159b34f1287079d4bdf7e77bc295@mailparser',
  stream: Base64Stream {
    _events: [Object: null prototype] {},
    _eventsCount: 0,
    _maxListeners: undefined,
    writable: true,
    checksum: Hash {
      _options: undefined,
      [Symbol(kHandle)]: Hash {},
      [Symbol(kState)]: [Object]
    },
    length: 5245,
    current: '',
    [Symbol(kCapture)]: false
  },
  checksum: '8d8c71ac84d23f92e171922eb89e1271',
  length: 5245
}

I want to attach those to an email using gmail-send which expects filepath.

Do I have to save the attachment to disk? If so, how?

Or can I somehow convert it "in memory"?

I tried

base64Data = attachment.stream;
require("fs").writeFile("out.png", base64Data, 'base64', function(err) {
  console.log(err);
});

but got a 0-length file.

CodePudding user response:

The method you are using to write the file is asynchronous so you need to resolve the promise to ensure the file write is successful. Alternatively you can do something synchronous like this

import * as fs from 'fs'
const base64Data = attachment.stream;
// Convert the base64 data to a buffer
const buffer = Buffer.from(base64Data, 'base64')
// Set a path for the temporary file
const tempFilePath = '~/some/place/somewhere/file.extension'
// Write the raw buffer to a file synchronously 
fs.writeFileSync(tempFilePath, buffer)
// TODO Do your stuff using the file, then delete the temporary file

fs.unlink(tempFilePath, (error) => {
  if (error) {
    console.error(error)
  }
})

Its hard to tell if it can be done in memory without looking at the specific module youre using, but this way would work with the file path.

  • Related