From 68b4a4fb90de8f05eaa4142af89094ebf24659c9 Mon Sep 17 00:00:00 2001 From: Liran Tal Date: Fri, 8 Feb 2019 11:40:23 +0200 Subject: [PATCH] feat(streams): refactor streams and buffer usage --- index.js | 100 ++++++++++++++++++++++++++++++++----------------------- 1 file changed, 58 insertions(+), 42 deletions(-) diff --git a/index.js b/index.js index 196f2af..bde6ba5 100644 --- a/index.js +++ b/index.js @@ -1,44 +1,60 @@ -var PNG = require('png-js'); -var charm = require('charm'); -var x256 = require('x256'); -var buffers = require('buffers'); -var es = require('event-stream'); - -var Stream = require('stream').Stream; - -module.exports = function (opts) { - if (!opts) opts = {}; - if (!opts.cols) opts.cols = 80; - - var c = charm(); - var bufs = buffers(); - - var ws = es.writeArray(function (err, bufs) { - var data = buffers(bufs).slice(); - var png = new PNG(data); - - png.decode(function (pixels) { - var dx = png.width / opts.cols; - var dy = 2 * dx; - - for (var y = 0; y < png.height; y += dy) { - for (var x = 0; x < png.width; x += dx) { - var i = (Math.floor(y) * png.width + Math.floor(x)) * 4; - - var ix = x256([ pixels[i], pixels[i+1], pixels[i+2] ]); - if (pixels[i+3] > 0) { - c.background(ix).write(' '); - } - else { - c.display('reset').write(' '); - } - } - c.display('reset').write('\r\n'); - } - - c.display('reset').end(); - }); +var PNG = require("png-js"); +var charm = require("charm"); +var x256 = require("x256"); + +var { Duplex } = require("stream"); + +class PictureTube extends Duplex { + constructor(opts = {}) { + super(); + this.data = []; + this.cols = opts.cols || 80; + + this.c = charm(); + + this.c.on("data", chunk => { + this.push(chunk); }); - - return es.duplex(ws, c); + + this.c.on("end", () => { + this.emit("end"); + }); + } + + _read() {} + + _write(chunk, encoding, callback) { + this.data.push(chunk); + callback(); + } + + _final(callback) { + var png = new PNG(Buffer.concat(this.data)); + + png.decode(pixels => { + var dx = png.width / this.cols; + var dy = 2 * dx; + + for (var y = 0; y < png.height; y += dy) { + for (var x = 0; x < png.width; x += dx) { + var i = (Math.floor(y) * png.width + Math.floor(x)) * 4; + + var ix = x256([pixels[i], pixels[i + 1], pixels[i + 2]]); + if (pixels[i + 3] > 0) { + this.c.background(ix).write(" "); + } else { + this.c.display("reset").write(" "); + } + } + this.c.display("reset").write("\r\n"); + } + + this.c.display("reset").end(); + callback(); + }); + } +} + +module.exports = opts => { + return new PictureTube(opts); };