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.
Install
Section titled “Install”pnpm add @kensio/pinyinjsRequires Node.js 22 or later, or a browser with ES modules. The package is ESM only.
Convert something
Section titled “Convert something”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"From the command line
Section titled “From the command line”The package also installs the pinyinjs command:
$ 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ǎonǐ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īngběijīng běijīng ㄅㄟˇ ㄐㄧㄥ pei³-ching¹ běijīng beeijing pei˨˩˦tɕiŋ˥Choose a guide
Section titled “Choose a guide”- Getting started covers setup and dictionary tiers.
- Converting explains contextual readings and custom pronunciations. Options lists the available settings.
- Orthography covers word spacing, capitals and punctuation. Sandhi explains tone changes.
- Confidence shows how to inspect uncertain readings. HTML output adds tone classes and readings above hanzi.
- Matching searches Chinese text with pinyin queries. Candidates finds Chinese words from pinyin, and checking grades a typed transcription.
- Slugs creates URL slugs and search keys.
- Script conversion converts simplified and traditional characters, including Taiwan and Hong Kong forms.
- Syllables, numbers and romanisation work without a dictionary.
- The CLI guide covers commands, flags and JSON output.
Licence
Section titled “Licence”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.
