# 内置模块

# 一、Crypto 模块

# Hash

  • 文件哈希计算

    流式读取大文件并计算哈希,避免内存溢出。

    import { createReadStream } from 'fs';
    import { createHash } from 'crypto';
    
    const calculateFileHash = (filePath, algorithm = 'md5') => {
      return new Promise((resolve, reject) => {
        const stream = createReadStream(filePath);
        const hash = createHash(algorithm);
    
        stream.on('data', (chunk) => hash.update(chunk));
        stream.on('end', () => resolve(hash.digest('hex')));
        stream.on('error', reject);
      });
    };
    
    // 使用示例
    calculateFileHash('./file.txt')
      .then(md5 => console.log('File MD5:', md5))
      .catch(console.error);
    
  • 字符串哈希计算

    直接对字符串内容进行哈希。

    import { createHash } from 'crypto';
    
    const hashString = (text, algorithm = 'sha256') => {
      return createHash(algorithm)
        .update(text)
        .digest('hex');
    };
    
    console.log('SHA-256:', hashString('Hello World'));