crc32-stream.js 989 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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 {Transform} = require('readable-stream');
  10. const {crc32} = require('crc');
  11. class CRC32Stream extends Transform {
  12. constructor(options) {
  13. super(options);
  14. this.checksum = Buffer.allocUnsafe(4);
  15. this.checksum.writeInt32BE(0, 0);
  16. this.rawSize = 0;
  17. }
  18. _transform(chunk, encoding, callback) {
  19. if (chunk) {
  20. this.checksum = crc32(chunk, this.checksum);
  21. this.rawSize += chunk.length;
  22. }
  23. callback(null, chunk);
  24. }
  25. digest(encoding) {
  26. const checksum = Buffer.allocUnsafe(4);
  27. checksum.writeUInt32BE(this.checksum >>> 0, 0);
  28. return encoding ? checksum.toString(encoding) : checksum;
  29. }
  30. hex() {
  31. return this.digest('hex').toUpperCase();
  32. }
  33. size() {
  34. return this.rawSize;
  35. }
  36. }
  37. module.exports = CRC32Stream;