npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

gb2312

v1.1.0

Published

A production-grade GB2312 encoding/decoding library for Node.js and browsers

Readme

gb2312

一款符合 GB2312-80 国家标准(《信息交换用汉字编码字符集·基本集》)的生产级编码/解码库,支持 ESM、CommonJS(CJS)和 IIFE 三种格式,可无缝运行于 Node.js 和浏览器环境。

核心特性

  • 多格式支持:适配 Node.js(ESM/CJS)和浏览器(IIFE,暴露全局变量 gb2312);
  • 零依赖:预构建 GB2312-Unicode 映射表,无需运行时拉取数据;
  • 类型安全:完整 TypeScript 支持,提供详细的类型定义;
  • 健壮可靠:自定义错误处理、无效字符替换机制,支持严格模式;
  • 全量覆盖:支持 GB2312-80 标准定义的全部 ~7445 个字符(含汉字、符号、ASCII 字符)。

安装

通过 npm(或 yarn/pnpm)安装:

npm install gb2312 --save

使用示例

1. ESM 格式(现代 Node.js/构建工具如 Vite/Rollup)

import { encode, decode, has, Gb2312Error } from 'gb2312';

// 将 Unicode 字符串编码为 GB2312 Buffer
try {
  const gb2312Buffer = encode('中华人民共和国', { strict: true });
  console.log(gb2312Buffer); // <Buffer d6 d0 bb aa c8 cb c3 f1 b9 b2 b9 fa>
} catch (err) {
  if (err instanceof Gb2312Error) {
    console.error('编码失败:', err.message);
  }
}

// 将 GB2312 Buffer 解码为 Unicode 字符串
const decodedStr = decode(Buffer.from([0xD6, 0xD0, 0xBB, 0xAA]));
console.log(decodedStr); // "中国"

// 检查字符是否在 GB2312 字符集中
console.log(has('中')); // true
console.log(has('𠀤')); // false(生僻字,不在 GB2312 范围内)

2. CommonJS 格式(传统 Node.js)

const { encode, decode } = require('gb2312');

// 编码字符串
const buffer = encode('测试GB2312编码');

// 解码 Buffer
const str = decode(buffer);
console.log(str); // "测试GB2312编码"

3. 浏览器环境(IIFE 格式)

通过 <script> 标签引入(自动暴露全局变量 gb2312):

<!-- 从 CDN 引入(请替换为最新版本) -->
<script src="https://unpkg.com/[email protected]/dist/gb2312.iife.js"></script>

<script>
  // 使用全局变量 `gb2312`
  try {
    const buffer = gb2312.encode('浏览器中使用GB2312');
    const str = gb2312.decode(buffer);
    console.log(str); // "浏览器中使用GB2312"

    // 检查字符是否支持
    console.log(gb2312.has('浏')); // true
  } catch (err) {
    if (err instanceof gb2312.Gb2312Error) {
      alert('错误:' + err.message);
    }
  }
</script>

API 文档

核心编码/解码方法

encode(str: string, options?: ConvertOptions): Buffer | Uint8Array

将 Unicode 字符串编码为 GB2312 格式的二进制数据(Node.js 中返回 Buffer,浏览器中返回 Uint8Array)。

| 参数 | 类型 | 说明 | |------------|-----------------|----------------------------------------------------------------------| | str | string | 待编码的 Unicode 字符串。 | | options | ConvertOptions| 可选配置:- replacement:无效字符的替换符(默认:?- strict:无效字符是否抛错(默认:false) |

示例

const buffer = encode('中文测试', { replacement: '□' });

decode(buffer: Buffer | Uint8Array, options?: ConvertOptions): string

将 GB2312 格式的二进制数据解码为 Unicode 字符串。

| 参数 | 类型 | 说明 | |------------|-----------------|----------------------------------------------------------------------| | buffer | Buffer/Uint8Array | 待解码的 GB2312 二进制数据。 | | options | ConvertOptions| 同 encode 的配置项。 |

示例

const str = decode(Buffer.from([0xD6, 0xD0, 0xCE, 0xC4]), { strict: true });
console.log(str); // "中文"

映射查询方法

toUnicode(code: Gb2312Code): UnicodeCode | null

将 16 位 GB2312 编码(如 “中” 的编码 0xD6D0)转换为对应的 Unicode 编码。

fromUnicode(code: UnicodeCode): Gb2312Code | null

将 Unicode 编码(如 “中” 的编码 20013)转换为对应的 16 位 GB2312 编码。

has(char: string): boolean

检查单个字符是否在 GB2312 字符集中(仅支持长度为 1 的字符串)。

getInfo(char: string): Gb2312Mapping | null

获取字符的详细编码信息(若字符不在 GB2312 中,返回 null)。

返回类型 Gb2312Mapping 结构

interface Gb2312Mapping {
  gb2312: Gb2312Code; // 16 位 GB2312 编码(如:0xD6D0)
  high: Gb2312Byte;   // 高位字节(如:0xD6)
  low: Gb2312Byte;    // 低位字节(如:0xD0)
  unicode: UnicodeCode;// Unicode 编码(如:20013)
  char: string;       // 字符本身(如:"中")
}

示例

const info = getInfo('中');
console.log(info); 
// { gb2312: 54992(即 0xD6D0), high: 214, low: 208, unicode: 20013, char: "中" }

工具方法

splitCode(code: Gb2312Code): { high: Gb2312Byte; low: Gb2312Byte }

将 16 位 GB2312 编码拆分为高位字节和低位字节。

combineBytes(high: Gb2312Byte, low: Gb2312Byte): Gb2312Code

将高位字节和低位字节合并为 16 位 GB2312 编码(无效字节会抛出 Gb2312Error)。

isReady(): boolean

检查库的映射表是否初始化完成(适用于异步环境)。

getInfoSummary(): { totalCount: number; firstChar: string; lastChar: string; version: string }

获取 GB2312 字符集的汇总信息(如总字符数、首个/最后一个字符)。

类型定义

所有类型均已导出,TypeScript 用户可直接使用:

// 16 位 GB2312 编码(范围:0xA1A1 ~ 0xF7FE)
type Gb2312Code = number;

// 8 位字节(范围:0x00 ~ 0xFF)
type Gb2312Byte = number;

// Unicode 编码点(范围:0x0000 ~ 0xFFFF)
type UnicodeCode = number;

// 编码/解码选项
interface ConvertOptions {
  replacement?: string; // 替换符(必须是单个字符)
  strict?: boolean;     // 严格模式(无效字符是否抛错)
}

// 自定义错误类型
class Gb2312Error extends Error {}

错误处理

通过导出的 Gb2312Error 类捕获库专属错误,避免与其他错误混淆:

import { encode, Gb2312Error } from 'gb2312';

try {
  // 严格模式下编码 GB2312 不支持的字符
  encode('𠀤', { strict: true });
} catch (err) {
  if (err instanceof Gb2312Error) {
    console.error('GB2312 错误:', err.message); 
    // "GB2312 错误:字符 "𠀤" (U+20024) 不在GB2312字符集中"
  }
}

兼容性说明

| 环境 | 支持情况 | 备注 | |---------------------|-------------------------|---------------------------------------| | Node.js | ✅ ESM (v14+) / CJS (v12+) | 二进制数据使用 Buffer。 | | 浏览器 | ✅ IIFE(所有现代浏览器) | 二进制数据使用 Uint8Array。 | | TypeScript | ✅ 完整支持 | 内置 .d.ts 类型定义文件。 | | 构建工具(Vite/Rollup) | ✅ ESM/CJS 自动适配 | 通过 package.json 自动识别格式。 |

许可证

MIT 许可证