| 1 | /** |
| 2 | * @file |
| 3 | * Example of Node.js API. |
| 4 | * |
| 5 | * @license |
| 6 | * Open Chinese Convert |
| 7 | * |
| 8 | * Copyright 2010-2026 Carbo Kuo and contributors |
| 9 | * |
| 10 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 11 | * you may not use this file except in compliance with the License. |
| 12 | * You may obtain a copy of the License at |
| 13 | * |
| 14 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 15 | * |
| 16 | * Unless required by applicable law or agreed to in writing, software |
| 17 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 19 | * See the License for the specific language governing permissions and |
| 20 | * limitations under the License. |
| 21 | */ |
| 22 | |
| 23 | import { OpenCC, OpenCCConfig } from './opencc'; |
| 24 | |
| 25 | declare const process: { |
| 26 | exitCode?: number; |
| 27 | }; |
| 28 | |
| 29 | const input = '汉字'; |
| 30 | |
| 31 | async function main(): Promise<void> { |
| 32 | console.log('OpenCC version', OpenCC.version); |
| 33 | |
| 34 | const converter = new OpenCC('s2t.json'); |
| 35 | |
| 36 | console.log('Sync API:', converter.convertSync(input)); |
| 37 | |
| 38 | const callbackResult = await new Promise<string>((resolve, reject) => { |
| 39 | converter.convert(input, (err: string | undefined, converted: string) => { |
| 40 | if (err) { |
| 41 | reject(new Error(err)); |
| 42 | return; |
| 43 | } |
| 44 | resolve(converted); |
| 45 | }); |
| 46 | }); |
| 47 | console.log('Callback API:', callbackResult); |
| 48 | |
| 49 | console.log('Promise API:', await converter.convertPromise(input)); |
| 50 | |
| 51 | const config: OpenCCConfig = { |
| 52 | name: 'Demo Inline Config', |
| 53 | conversion_chain: [ |
| 54 | { |
| 55 | dict: { |
| 56 | type: 'inline', |
| 57 | entries: { |
| 58 | '鼠标': '滑鼠', |
| 59 | '软件': '軟體', |
| 60 | }, |
| 61 | }, |
| 62 | }, |
| 63 | ], |
| 64 | }; |
| 65 | |
| 66 | const inlineConverter = OpenCC.fromConfig(config); |
| 67 | console.log('Inline config:', inlineConverter.convertSync('鼠标和软件')); |
| 68 | } |
| 69 | |
| 70 | main().catch((err: unknown) => { |
| 71 | console.error(err); |
| 72 | process.exitCode = 1; |
| 73 | }); |