Last active
February 29, 2024 23:59
-
-
Save andrei-tofan/b75082574544aee19de1295a48323ad5 to your computer and use it in GitHub Desktop.
node.js writable buffer stream (pdfkit example)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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')); | |
}); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 } |
Hi, modify the export of the class stream.js from module.exports = writableBufferStream
to module.exports = { writableBufferStream }
and stream.WritableBufferStream();
it works
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
I'm getting the error:
… on:
let writeStream = new stream.WritableBufferStream()
I'm using Node v14.7.0
In the end:
… and:
let writeStream = new writableBufferStream()