UNPKG

1.29 kBJavaScriptView Raw
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
11const {DeflateRaw} = require('zlib');
12
13const crc32 = require('crc-32');
14
15class DeflateCRC32Stream extends DeflateRaw {
16 constructor(options) {
17 super(options);
18
19 this.checksum = Buffer.allocUnsafe(4);
20 this.checksum.writeInt32BE(0, 0);
21
22 this.rawSize = 0;
23 this.compressedSize = 0;
24 }
25
26 push(chunk, encoding) {
27 if (chunk) {
28 this.compressedSize += chunk.length;
29 }
30
31 return super.push(chunk, encoding);
32 }
33
34 _transform(chunk, encoding, callback) {
35 if (chunk) {
36 this.checksum = crc32.buf(chunk, this.checksum) >>> 0;
37 this.rawSize += chunk.length;
38 }
39
40 super._transform(chunk, encoding, callback)
41 }
42
43 digest(encoding) {
44 const checksum = Buffer.allocUnsafe(4);
45 checksum.writeUInt32BE(this.checksum >>> 0, 0);
46 return encoding ? checksum.toString(encoding) : checksum;
47 }
48
49 hex() {
50 return this.digest('hex').toUpperCase();
51 }
52
53 size(compressed = false) {
54 if (compressed) {
55 return this.compressedSize;
56 } else {
57 return this.rawSize;
58 }
59 }
60}
61
62module.exports = DeflateCRC32Stream;