Created
March 21, 2021 12:19
-
-
Save amishshah/1f7e202dfb8f5595ebb19b9338a4d8f2 to your computer and use it in GitHub Desktop.
Allows for writing a Node.js object stream to a non-object format and then later parsing it.
This file contains hidden or 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
'use strict'; | |
const { Transform } = require('stream'); | |
exports.Serialiser = class Serialiser extends Transform { | |
constructor(options) { | |
super({ writableObjectMode: true, ...options }); | |
} | |
_transform(chunk, encoding, callback) { | |
const size = Buffer.allocUnsafe(2); | |
size.writeUInt16LE(chunk.length); | |
this.push(Buffer.concat([ | |
size, | |
chunk, | |
])); | |
callback(); | |
} | |
}; | |
exports.Deserialiser = class Deserialiser extends Transform { | |
constructor(options) { | |
super({ readableObjectMode: true, ...options }); | |
this.remainder = Buffer.alloc(0); | |
} | |
_transform(chunk, encoding, callback) { | |
this.remainder = Buffer.concat([this.remainder, chunk]); | |
this.readChunk(); | |
callback(); | |
} | |
_flush(cb) { | |
this.readChunk(true); | |
cb(); | |
} | |
readChunk(force = false) { | |
const buffer = this.remainder; | |
if (buffer.length === 0) { | |
return; | |
} | |
const size = buffer.readUInt16LE(0); | |
const data = buffer.slice(2); | |
if (data.length >= size) { | |
const canContinue = this.push(data.slice(0, size)); | |
this.remainder = data.slice(size); | |
if (canContinue || force) { | |
this.readChunk(force); | |
} | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage with
prism-media
:Saving an Opus stream to filesystem:
Later re-reading the Opus stream:
Implementation notes