Debian Codegraph @

node/demo.js

raw symbols SCIP
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 /**
24 * @example node/demo.js
25 * This is an example of how to use the Node.js API.
26 */
27
28 // In your project you should replace './opencc' with 'opencc'
29 const { OpenCC } = require('./opencc');
30
31 const input = '汉字';
32
33 async function main() {
34 console.log('OpenCC version', OpenCC.version);
35
36 const converter = new OpenCC('s2t.json');
37
38 console.log('Sync API:', converter.convertSync(input));
39
40 const callbackResult = await new Promise((resolve, reject) => {
41 converter.convert(input, (err, converted) => {
42 if (err) {
43 reject(new Error(err));
44 return;
45 }
46 resolve(converted);
47 });
48 });
49 console.log('Callback API:', callbackResult);
50
51 console.log('Promise API:', await converter.convertPromise(input));
52
53 const config = {
54 name: 'Demo Inline Config',
55 conversion_chain: [
56 {
57 dict: {
58 type: 'inline',
59 entries: {
60 '鼠标': '滑鼠',
61 '软件': '軟體',
62 },
63 },
64 },
65 ],
66 };
67
68 const inlineConverter = OpenCC.fromConfig(config);
69 console.log('Inline config:', inlineConverter.convertSync('鼠标和软件'));
70 }
71
72 main().catch((err) => {
73 console.error(err);
74 process.exitCode = 1;
75 });