zlib.crc32(data[, value])
data<string> | <Buffer> | <TypedArray> | <DataView> 当data是字符串时,它将在用于计算之前被编码为 UTF-8。value<integer> 可选的起始值。它必须是一个32位无符号整数。默认值:0- 返回:<integer> 一个包含校验和的 32 位无符号整数。
计算 data 的 32 位 循环冗余校验 校验和。如果指定了 value,则将其用作校验和的起始值,否则使用 0 作为起始值。
【Computes a 32-bit Cyclic Redundancy Check checksum of data. If
value is specified, it is used as the starting value of the checksum,
otherwise, 0 is used as the starting value.】
CRC 算法旨在计算校验和并检测数据传输中的错误。它不适用于密码学身份验证。
【The CRC algorithm is designed to compute checksums and to detect error in data transmission. It's not suitable for cryptographic authentication.】
为了与其他 API 保持一致,如果 data 是字符串,它将在用于计算之前以 UTF-8 编码。如果用户仅使用 Node.js 来计算和匹配校验和,这与默认使用 UTF-8 编码的其他 API 可以很好地配合。
【To be consistent with other APIs, if the data is a string, it will
be encoded with UTF-8 before being used for computation. If users only
use Node.js to compute and match the checksums, this works well with
other APIs that uses the UTF-8 encoding by default.】
一些第三方 JavaScript 库会基于 str.charCodeAt() 对字符串计算校验和,以便在浏览器中运行。 如果用户希望匹配在浏览器中由此类库计算的校验和,最好在 Node.js 中使用相同的库(如果它也可以在 Node.js 中运行)。 如果用户必须使用 zlib.crc32() 来匹配由此类第三方库生成的校验和:
【Some third-party JavaScript libraries compute the checksum on a
string based on str.charCodeAt() so that it can be run in browsers.
If users want to match the checksum computed with this kind of library
in the browser, it's better to use the same library in Node.js
if it also runs in Node.js. If users have to use zlib.crc32() to
match the checksum produced by such a third-party library:】
- 如果库接受
Uint8Array作为输入,请在浏览器中使用TextEncoder将字符串编码为 UTF-8 的Uint8Array,并在浏览器中基于 UTF-8 编码的字符串计算校验和。 - 如果库只接受字符串并基于
str.charCodeAt()计算数据,那么在 Node.js 端,将字符串使用Buffer.from(str, 'utf16le')转换为缓冲区。
import zlib from 'node:zlib';
import { Buffer } from 'node:buffer';
let crc = zlib.crc32('hello'); // 907060870
crc = zlib.crc32('world', crc); // 4192936109
crc = zlib.crc32(Buffer.from('hello', 'utf16le')); // 1427272415
crc = zlib.crc32(Buffer.from('world', 'utf16le'), crc); // 4150509955const zlib = require('node:zlib');
const { Buffer } = require('node:buffer');
let crc = zlib.crc32('hello'); // 907060870
crc = zlib.crc32('world', crc); // 4192936109
crc = zlib.crc32(Buffer.from('hello', 'utf16le')); // 1427272415
crc = zlib.crc32(Buffer.from('world', 'utf16le'), crc); // 4150509955