New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details
Socket
Book a DemoSign in
Socket

gb2312

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

gb2312

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

latest
npmnpm
Version
1.1.0
Version published
Weekly downloads
6
500%
Maintainers
1
Weekly downloads
 
Created
Source

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/gb2312@1.0.0/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)。

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

示例

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

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

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

参数类型说明
bufferBuffer/Uint8Array待解码的 GB2312 二进制数据。
optionsConvertOptionsencode 的配置项。

示例

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 许可证

Keywords

gb2312

FAQs

Package last updated on 14 Oct 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts