Charles Lyding b60b7dacfa refactor(@angular-devkit/schematics): avoid double file access reading JSON files
The file system engine hosts for schematics were using a helper method to
read JSON files that was performing both an exist and read call. Besides
causing two file system calls, this also has a potential race condition
where the file may not exist by the time the read call is made. To avoid
this, a try/catch is used with the read call to handle the not existing
case.
2024-06-26 08:31:10 -07:00

39 lines
1.0 KiB
TypeScript

/**
* @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 { FileDoesNotExistException } from '@angular-devkit/schematics';
import { readFileSync } from 'fs';
import { ParseError, parse, printParseErrorCode } from 'jsonc-parser';
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;
}