1/**
2 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import Log from './Log';
17import FileIo from '@ohos.fileio';
18
19const DFAULT_SIZE = 4096;
20const CHAR_CODE_AT_INDEX = 0;
21const TAG = 'ReadConfigUtil';
22
23export class ReadConfigUtil {
24  readConfigFile(fileName: string): any {
25    Log.showDebug(TAG, `readConfigFile fileName:${fileName}`);
26    try {
27      let stream = FileIo.createStreamSync(fileName, 'r');
28      Log.showDebug(TAG, `readConfigFile stream:${JSON.stringify(stream)}`);
29      let buf = new ArrayBuffer(DFAULT_SIZE);
30      let len = stream.readSync(buf);
31      Log.showDebug(TAG, `readConfigFile len:${len}`);
32      let arr = new Uint8Array(buf);
33      let charAt = ' '.charCodeAt(CHAR_CODE_AT_INDEX);
34      for (let i = len;i < DFAULT_SIZE; i++) {
35        arr[i] = charAt;
36      }
37      let content = String.fromCharCode.apply(null, arr);
38      stream.closeSync();
39      Log.showDebug(TAG, `readConfigFile content:${JSON.stringify(content)}`);
40      return JSON.parse(content);
41    } catch (error) {
42      Log.showError(TAG, `readConfigFile error:${JSON.stringify(error)}`);
43    }
44  }
45}
46
47let readConfigUtil = new ReadConfigUtil();
48
49export default readConfigUtil;
50