使用npm包:pinyin,这还是一个两年前发布的神库吧。
1、安装
yarn add pinyin
2、使用
const pinyin = require("pinyin");console.log(pinyin("中心"));    // [ [ 'zhōng' ], [ 'xīn' ] ]
console.log(pinyin("中心", {heteronym: true               // 启用多音字模式
}));                            // [ [ 'zhōng', 'zhòng' ], [ 'xīn' ] ]
console.log(pinyin("中心", {heteronym: true,              // 启用多音字模式segment: true                 // 启用分词,以解决多音字问题。
}));                            // [ [ 'zhōng' ], [ 'xīn' ] ]
console.log(pinyin("中心", {style: pinyin.STYLE_INITIALS, // 设置拼音风格heteronym: true
}));                            // [ [ 'zh' ], [ 'x' ] ]