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