• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2023 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
16const JSON5 = require("json5");
17
18module.exports = class ReadJsonPlugin {
19  apply(resolver) {
20    if (resolver && resolver.fileSystem && resolver.fileSystem.readFile) {
21      resolver.fileSystem.readJson = (filepath, callback) => {
22        resolver.fileSystem.readFile(filepath, (error, content) => {
23          if (error) {
24            return callback(error);
25          }
26          if (!content || content.length === 0) {
27            return callback(new Error("No file content"));
28          }
29          let data;
30          try {
31            if (/\.json5$/.test(filepath)) {
32              data = JSON5.parse(content.toString("utf-8"));
33            } else {
34              data = JSON.parse(content.toString("utf-8"));
35            }
36          } catch (e) {
37            return callback(e);
38          }
39          callback(null, data);
40        });
41      };
42    }
43  }
44};
45