Skip to content

Instantly share code, notes, and snippets.

@andrei-tofan
Last active February 29, 2024 23:59
Show Gist options
  • Save andrei-tofan/b75082574544aee19de1295a48323ad5 to your computer and use it in GitHub Desktop.
Save andrei-tofan/b75082574544aee19de1295a48323ad5 to your computer and use it in GitHub Desktop.
node.js writable buffer stream (pdfkit example)
/**
* Convert PDFDocument to Base64
*/
const PDFDocument = require('pdfkit');
const stream = require('./stream');
// crate document and write stream
let doc = new PDFDocument();
let writeStream = new stream.WritableBufferStream();
// pip the document to write stream
doc.pipe(writeStream);
// add some content
doc.text('Some text!', 100, 100);
// end document
doc.end()
// wait for the writing to finish
writeStream.on('finish', () => {
// console log pdf as bas64 string
console.log(writeStream.toBuffer().toString('base64'));
});
const stream = require('stream');
/**
* Simple writable buffer stream
* @docs: https://nodejs.org/api/stream.html#stream_writable_streams
*/
class WritableBufferStream extends stream.Writable {
constructor(options) {
super(options);
this._chunks = [];
}
_write (chunk, enc, callback) {
this._chunks.push(chunk);
return callback(null);
}
_destroy(err, callback) {
this._chunks = null;
return callback(null);
}
toBuffer() {
return Buffer.concat(this._chunks);
}
}
module.exports = { WritableBufferStream }
@fnovello
Copy link

Hi, modify the export of the class stream.js from module.exports = writableBufferStream to module.exports = { writableBufferStream } and stream.WritableBufferStream(); it works

@andrei-tofan
Copy link
Author

Thx for the feedback, added the export.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment