Skip to content

Commit

Permalink
refactor(@angular-devkit/schematics): avoid double file access readin…
Browse files Browse the repository at this point in the history
…g 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.
  • Loading branch information
clydin authored and dgp1130 committed Jun 26, 2024
1 parent eb52981 commit b60b7da
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions packages/angular_devkit/schematics/tools/file-system-utility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,22 @@

import { JsonValue } from '@angular-devkit/core';
import { FileDoesNotExistException } from '@angular-devkit/schematics';
import { existsSync, readFileSync } from 'fs';
import { readFileSync } from 'fs';
import { ParseError, parse, printParseErrorCode } from 'jsonc-parser';

export function readJsonFile(path: string): JsonValue {
if (!existsSync(path)) {
throw new FileDoesNotExistException(path);
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(readFileSync(path, 'utf-8'), errors, { allowTrailingComma: true });
const content = parse(data, errors, { allowTrailingComma: true }) as JsonValue;

if (errors.length) {
const { error, offset } = errors[0];
Expand Down

0 comments on commit b60b7da

Please sign in to comment.