简体   繁体   English

将 Base64 stream 转换为文件 object 而不保存

[英]Converting Base64 stream to file object without saving

In Node.js, I want to use a Base64Stream from one module and use it as a file in another.在 Node.js 中,我想使用一个模块中的Base64Stream并将其用作另一个模块中的文件。

I am getting email attachments from mail-listener2 which return like this:我从mail-listener2收到 email 附件,返回如下:

{
  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 .我想使用需要filepathgmail-send它们附加到 email。

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.但得到了一个 0 长度的文件。

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.您用于写入文件的方法是异步的,因此您需要解析 promise 以确保文件写入成功。 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.如果不查看您正在使用的特定模块,很难判断它是否可以在 memory 中完成,但这种方式适用于文件路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM