簡體   English   中英

使用 nodejs fs 從 email 保存 PDF

[英]Save PDF from email using nodejs fs

我正在使用名為mail-notifier的 npm package 來處理新的電子郵件,我希望能夠將附件保存到文件夾中,節點 fs 似乎能夠做到這一點,但我無法弄清楚。

這是附件如何進入的示例。

{
  contentType: 'application/pdf',
  transferEncoding: 'base64',
  contentDisposition: 'attachment',
  fileName: 'somedocument.pdf',
  generatedFileName: 'somedocument.pdf',
  contentId: 'f0b4b8a7983590814558ce2976c71629@mailparser',
  checksum: 'bc084ae645fd6e6da0aa4d74c9b95ae6',
  length: 29714,
  content: <Buffer 25 50 44 46 2d 31 2e 34 0a 25 d3 eb e9 e1 0a 31 20 30 20 6f 62 6a 0a 3c 3c 2f 43 72 65 61 74 6f 72 20 28 43 68 72 6f 6d 69 75 6d 29 0a 2f 50 72 6f 64 ... 29664 more bytes>
}

這是我從其他地方看到的嘗試過的,但它說

mail.attachments.forEach((attachment) => {
 var output = fs.createWriteStream('/example-folder/' + attachment.generatedFileName);
 attachment.stream.pipe(output);
});

盡管說 stream.pipe 不是 function,但會引發錯誤。

是否要將緩沖區傳遞給寫入 stream? 緩沖區與它有什么關系嗎?

試試stream

const { PassThrough } = require('stream');
 
 
mail.attachments.forEach((attachment) => {
    var output = fs.createWriteStream('/example-folder/' + attachment.generatedFileName);
    var pass = new PassThrough();
    pass.end(attachment.content);
    pass.pipe(output);
});

由於文件作為Buffer存儲在attachment.content中,因此有兩種使用方法:

  1. 您可以使用fs.writeFile('/example-folder/' + attachment.generatedFileName, attachment.content ); 或者
  2. output.write(attachment.content); .end如果你也想關閉文件)

(1) 使用非流式 API 而 (2) 使用流式 API 但沒有性能優勢,因為整個文件已經在 memory

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM