@@ -728,15 +728,38 @@ Computes a 32-bit [Cyclic Redundancy Check][] checksum of `data`. If
728
728
` value ` is specified, it is used as the starting value of the checksum,
729
729
otherwise, 0 is used as the starting value.
730
730
731
+ The CRC algorithm is designed to compute checksums and to detect error
732
+ in data transmission. It's not suitable for cryptographic authentication.
733
+
734
+ To be consistent with other APIs, if the ` data ` is a string, it will
735
+ be encoded with UTF-8 before being used for computation. If users only
736
+ uses Node.js to compute and check the checksums, this works well with
737
+ other APIs that uses the UTF-8 encoding by default.
738
+
739
+ Some third-party JavaScript libraries that compute the checksum on a
740
+ string based on ` str.charCodeAt() ` so that it can be run in browsers.
741
+ If users want to match the checksum computed with this kind of library
742
+ from the browser, it's better to use the same library in Node.js
743
+ if it also runs in Node.js. If users have to use ` zlib.crc32() ` to
744
+ match the checksum produced by such a third-party library:
745
+
746
+ 1 . If the library accepts ` Uint8Array ` as input, use ` TextEncoder `
747
+ in the browser to encode the string into a ` Uint8Array ` with UTF-8
748
+ encoding, and compute the checksum based on the UTF-8 encoded string
749
+ in the browser.
750
+ 2 . If the library only takes a string and compute the data based on
751
+ ` str.charCodeAt() ` , on the Node.js side, convert the string into
752
+ a buffer using ` Buffer.from(str, 'utf16le') ` .
753
+
731
754
``` mjs
732
755
import zlib from ' node:zlib' ;
733
756
import { Buffer } from ' node:buffer' ;
734
757
735
758
let crc = zlib .crc32 (' hello' ); // 907060870
736
759
crc = zlib .crc32 (' world' , crc); // 4192936109
737
760
738
- crc = zlib .crc32 (Buffer .from (' hello' )); // 907060870
739
- crc = zlib .crc32 (Buffer .from (' world' ), crc); // 4192936109
761
+ crc = zlib .crc32 (Buffer .from (' hello' , ' utf16le ' )); // 1427272415
762
+ crc = zlib .crc32 (Buffer .from (' world' , ' utf16le ' ), crc); // 4150509955
740
763
```
741
764
742
765
``` cjs
@@ -746,8 +769,8 @@ const { Buffer } = require('node:buffer');
746
769
let crc = zlib .crc32 (' hello' ); // 907060870
747
770
crc = zlib .crc32 (' world' , crc); // 4192936109
748
771
749
- crc = zlib .crc32 (Buffer .from (' hello' )); // 907060870
750
- crc = zlib .crc32 (Buffer .from (' world' ), crc); // 4192936109
772
+ crc = zlib .crc32 (Buffer .from (' hello' , ' utf16le ' )); // 1427272415
773
+ crc = zlib .crc32 (Buffer .from (' world' , ' utf16le ' ), crc); // 4150509955
751
774
```
752
775
753
776
### ` zlib.close([callback]) `
0 commit comments