ScanStream.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const stream_1 = require("stream");
  4. /**
  5. * Convenient class to convert the process of scaning keys to a readable stream.
  6. *
  7. * @export
  8. * @class ScanStream
  9. * @extends {Readable}
  10. */
  11. class ScanStream extends stream_1.Readable {
  12. constructor(opt) {
  13. super(opt);
  14. this.opt = opt;
  15. this._redisCursor = "0";
  16. this._redisDrained = false;
  17. }
  18. _read() {
  19. if (this._redisDrained) {
  20. this.push(null);
  21. return;
  22. }
  23. const args = [this._redisCursor];
  24. if (this.opt.key) {
  25. args.unshift(this.opt.key);
  26. }
  27. if (this.opt.match) {
  28. args.push("MATCH", this.opt.match);
  29. }
  30. if (this.opt.count) {
  31. args.push("COUNT", String(this.opt.count));
  32. }
  33. this.opt.redis[this.opt.command](args, (err, res) => {
  34. if (err) {
  35. this.emit("error", err);
  36. return;
  37. }
  38. this._redisCursor = res[0] instanceof Buffer ? res[0].toString() : res[0];
  39. if (this._redisCursor === "0") {
  40. this._redisDrained = true;
  41. }
  42. this.push(res[1]);
  43. });
  44. }
  45. close() {
  46. this._redisDrained = true;
  47. }
  48. }
  49. exports.default = ScanStream;