forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile-system-utility.ts
38 lines (33 loc) · 1.05 KB
/
file-system-utility.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { JsonValue } from '@angular-devkit/core';
import { ParseError, parse, printParseErrorCode } from 'jsonc-parser';
import { readFileSync } from 'node:fs';
import { FileDoesNotExistException } from '../src/exception/exception';
export function readJsonFile(path: string): JsonValue {
let data;
try {
data = readFileSync(path, 'utf-8');
} catch (e) {
if (e && typeof e === 'object' && 'code' in e && e.code === 'ENOENT') {
throw new FileDoesNotExistException(path);
}
throw e;
}
const errors: ParseError[] = [];
const content = parse(data, errors, { allowTrailingComma: true }) as JsonValue;
if (errors.length) {
const { error, offset } = errors[0];
throw new Error(
`Failed to parse "${path}" as JSON AST Object. ${printParseErrorCode(
error,
)} at location: ${offset}.`,
);
}
return content;
}