Save PDF from email using nodejs fs

1.1k Views Asked by At

I am using an npm package called mail-notifier to process new emails as they come in, I want to be able to save attachments to a folder and node fs seems to be able to do this but I can't figure it out.

This is an example of how the an attachment comes in.

{
  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>
}

This is what i have tried from what i have seen elsewhere but it says

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

This throws and error though saying the stream.pipe is not a function.

Am i ment to pass the buffer to the write stream? Does the buffer have anything to do with it?

2

There are 2 best solutions below

1
On BEST ANSWER

Since the file is stored in the attachment.content as a Buffer, there are two methods to use:

  1. you can use fs.writeFile('/example-folder/' + attachment.generatedFileName, attachment.content ); or
  2. output.write(attachment.content);(.end if you want to close the file as well)

(1) uses the non-streaming API while (2) uses the streaming API but has no performance benefit since the whole file is already in memory

0
On

Try 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);
});