← Runnable Projects

阅读中文版本

CRC32 Checksum CLI

A dependency-free Node CLI that prints the CRC32 checksum of a file or stdin as an eight-digit hex string, using a precomputed lookup table.

beginnerjavascriptunverified

Project

node-crc32-cli

Entry point: crc32.mjs

Install

node --version

Run

node crc32.mjs package.json

Test

node --test crc32.test.mjs

Expected output

Prints the eight-character hexadecimal CRC32 of the input, for example cbf43926 for the ASCII string 123456789.

Dependencies

  • node >=20

What it does

Reads a file as a stream, updates a CRC32 register chunk by chunk, and prints the result. A 256-entry lookup table makes the inner loop a table lookup instead of eight bit operations.

import { createReadStream } from 'node:fs';

const TABLE = new Uint32Array(256);
for (let n = 0; n < 256; n++) {
  let c = n;
  for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
  TABLE[n] = c >>> 0;
}

export function crc32(buf, seed = 0) {
  let crc = (seed ^ 0xffffffff) >>> 0;
  for (const byte of buf) crc = TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8);
  return (crc ^ 0xffffffff) >>> 0;
}

const path = process.argv[2];
let crc = 0xffffffff;
const stream = path ? createReadStream(path) : process.stdin;
for await (const chunk of stream) crc = crc32(chunk, crc ^ 0xffffffff);
console.log(((crc ^ 0xffffffff) >>> 0).toString(16).padStart(8, '0'));

Run and verify

node crc32.mjs package.json

Run the test command to check the implementation: node --test crc32.test.mjs.

Expected Output

The canonical check value for the ASCII bytes of 123456789 is CBF43926. The tool prints the checksum in lowercase hex:

cbf43926

Limitations

CRC32 detects accidental corruption but is not a cryptographic hash; do not use it to verify integrity against a malicious actor.