在 Node.js 中,我想使用Base64Stream一個模塊中的一個并將其用作另一個模塊中的檔案。
我收到的電子郵件附件是mail-listener2這樣回傳的:
{
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
}
我想將這些附加到使用gmail-sendwhich expects的電子郵件中filepath。
我必須將附件保存到磁盤嗎?如果是這樣,怎么做?
或者我可以以某種方式將其“在記憶體中”轉換嗎?
我試過
base64Data = attachment.stream;
require("fs").writeFile("out.png", base64Data, 'base64', function(err) {
console.log(err);
});
但得到了一個長度為 0 的檔案。
uj5u.com熱心網友回復:
您用于寫入檔案的方法是異步的,因此您需要決議承諾以確保檔案寫入成功。或者你可以做一些像這樣同步的事情
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)
}
})
如果不查看您正在使用的特定模塊,很難判斷它是否可以在記憶體中完成,但這種方式適用于檔案路徑。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/426554.html
標籤:节点.js
下一篇:我如何檢查hits是否有價值?
