deflate-crc32-stream.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /**
  2. * node-crc32-stream
  3. *
  4. * Copyright (c) 2014 Chris Talkington, contributors.
  5. * Licensed under the MIT license.
  6. * https://github.com/archiverjs/node-crc32-stream/blob/master/LICENSE-MIT
  7. */
  8. 'use strict';
  9. const {DeflateRaw} = require('zlib');
  10. const {crc32} = require('crc');
  11. class DeflateCRC32Stream extends DeflateRaw {
  12. constructor(options) {
  13. super(options);
  14. this.checksum = Buffer.allocUnsafe(4);
  15. this.checksum.writeInt32BE(0, 0);
  16. this.rawSize = 0;
  17. this.compressedSize = 0;
  18. }
  19. push(chunk, encoding) {
  20. if (chunk) {
  21. this.compressedSize += chunk.length;
  22. }
  23. return super.push(chunk, encoding);
  24. }
  25. write(chunk, enc, cb) {
  26. if (chunk) {
  27. this.checksum = crc32(chunk, this.checksum);
  28. this.rawSize += chunk.length;
  29. }
  30. return super.write(chunk, enc, cb);
  31. }
  32. digest(encoding) {
  33. const checksum = Buffer.allocUnsafe(4);
  34. checksum.writeUInt32BE(this.checksum >>> 0, 0);
  35. return encoding ? checksum.toString(encoding) : checksum;
  36. }
  37. hex() {
  38. return this.digest('hex').toUpperCase();
  39. }
  40. size(compressed = false) {
  41. if (compressed) {
  42. return this.compressedSize;
  43. } else {
  44. return this.rawSize;
  45. }
  46. }
  47. }
  48. module.exports = DeflateCRC32Stream;