'How to check if a stream is base64 encoded?
I'm trying to understand the node js streams and I'm experimenting a bit, so this may be a dumb question.
In the example I'm using a Duplex stream to check if the stream is fully encoded as base64:
const { Duplex } = require("stream");
const fs = require("fs");
class IsBase64Encoded extends Duplex {
constructor(callback) {
super();
this.isBase64 = true;
this.isBase64Callback = callback;
}
_read() {}
_write(chunk, encoding, callback) {
if (
this.isBase64 &&
Buffer.from(chunk.toString(), "base64").toString("base64") !==
chunk.toString()
) {
this.isBase64 = false;
}
this.push(chunk);
callback();
}
_final() {
this.isBase64Callback(this.isBase64);
this.push(null);
}
}
const inputStream = fs.createReadStream(`${__dirname}/sample`);
const callback = (isBase64) => {
console.log("IS STREAM BASE64 ENCODED: ", isBase64);
};
inputStream.pipe(new IsBase64Encoded(callback));
Now, is this an actual legit way to do such a thing? I'd guess it is, since it seems to work, but I want to understand if there are any side effects.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
