Skip to content

Commit d9057fc

Browse files
committed
fixup! zlib: expose zlib.crc32()
1 parent 53fb0e4 commit d9057fc

File tree

1 file changed

+27
-4
lines changed

1 file changed

+27
-4
lines changed

doc/api/zlib.md

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -728,15 +728,38 @@ Computes a 32-bit [Cyclic Redundancy Check][] checksum of `data`. If
728728
`value` is specified, it is used as the starting value of the checksum,
729729
otherwise, 0 is used as the starting value.
730730

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+
731754
```mjs
732755
import zlib from 'node:zlib';
733756
import { Buffer } from 'node:buffer';
734757

735758
let crc = zlib.crc32('hello'); // 907060870
736759
crc = zlib.crc32('world', crc); // 4192936109
737760

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
740763
```
741764

742765
```cjs
@@ -746,8 +769,8 @@ const { Buffer } = require('node:buffer');
746769
let crc = zlib.crc32('hello'); // 907060870
747770
crc = zlib.crc32('world', crc); // 4192936109
748771

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
751774
```
752775

753776
### `zlib.close([callback])`

0 commit comments

Comments
 (0)