Skip to content

PinyinJS

PinyinJS converts Chinese characters (hanzi) to pinyin in JavaScript and TypeScript. It runs in Node.js and browsers. Try the playground or follow the setup below.

Terminal window
pnpm add @kensio/pinyinjs

Requires Node.js 22 or later, or a browser with ES modules. The package is ESM only.

Load a dictionary before converting text. Dictionary data is separate from the JavaScript bundle and loads asynchronously. Reuse the loaded dictionary across conversions.

import { convert, loadDictionary } from "@kensio/pinyinjs";
import { fileSource } from "@kensio/pinyinjs/node";
const source = fileSource("node_modules/@kensio/pinyinjs/data");
const dictionary = await loadDictionary(source, "full");
convert(dictionary, "银行"); // "yínháng"
convert(dictionary, "行长"); // "hángzhǎng"
convert(dictionary, "我要去北京。"); // "Wǒ yào qù Běijīng."

In a browser, serve the package’s data/ directory and fetch it:

import { convert, fetchSource, loadDictionary } from "@kensio/pinyinjs";
const dictionary = await loadDictionary(fetchSource("/data"), "standard");
convert(dictionary, "长城"); // "Chángchéng"

The package also installs the pinyinjs command:

Terminal window
$ pinyinjs convert 我要去北京。
Wǒ yào qù Běijīng.
$ pinyinjs slug 我想学中文。
wo3-xiang3-xue2-zhong1wen2
$ pinyinjs script 我们后来发现他的头发掉得很厉害。 --to zh-Hant
我們後來發現他的頭髮掉得很厲害。
$ pinyinjs explain 银行
银行 yínháng
yín locked
háng word xíng +24.6 héng +26.6 hàng +27.6
$ pinyinjs syllable nǐhǎo
nǐhǎo nǐ hǎo
nǐ n + i, tone 3 nǐ ni3 ni³
hǎo h + ao, tone 3 hǎo hao3 hao³
$ pinyinjs transcribe běijīng
běijīng běijīng ㄅㄟˇ ㄐㄧㄥ pei³-ching¹ běijīng beeijing pei˨˩˦tɕiŋ˥

The code is licensed under Apache-2.0. The compiled dictionaries in data/ include CC-CEDICT data and carry CC BY-SA 4.0 share-alike terms.