'How to convert ReadableStream into ReadStream in NodeJS?
I'm using nodemailer, and pdfmake to create a pdf, and send it in the email's attachments. I don't have too much experience with file handling in NodeJS, and I can't make it work.
See example where the file is saved. As I've checked the types, createPdfKitDocument returns an extension of NodeJS.ReadableStream.
In nodemailer I can include attachments as Stream or Readable See documentation.
However, I'm not able to send the attachment without saving it, and give the path to the file.
I tried to provide the ReadableStream returned from createPdfKitDocument as is, it result in hanging promise. I tried to wrap it with Readable.from(), it didn't work. I tried to call .read() on the result, and it didn't result in hanging promise, but the pdf cannot be opened.
Any ideas how can I convert a ReadableStream to Readable, or Buffer?
Solution 1:[1]
NodeJS.ReadableStream type streams are used in older NodeJS libraries and versions. You can use the wrap method in Readable to convert NodeJS.ReadableStream to Readable stream.
const { OldReader } = require('./old-api-module.js');
const { Readable } = require('node:stream');
const oreader = new OldReader(); // will return stream of NodeJS.ReadableStream
const myReader = new Readable().wrap(oreader);
myReader.on('readable', () => {
myReader.read(); // etc.
});
Ref: https://nodejs.org/api/stream.html#stream_readable_wrap_stream. For additional info do refer this as well https://nodejs.org/api/stream.html#compatibility-with-older-nodejs-versions
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | v1shva |
