Skip to content

Commit b60b7da

Browse files
clydindgp1130
authored andcommitted
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.
1 parent eb52981 commit b60b7da

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

packages/angular_devkit/schematics/tools/file-system-utility.ts

+10-4
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,22 @@
88

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

1414
export function readJsonFile(path: string): JsonValue {
15-
if (!existsSync(path)) {
16-
throw new FileDoesNotExistException(path);
15+
let data;
16+
try {
17+
data = readFileSync(path, 'utf-8');
18+
} catch (e) {
19+
if (e && typeof e === 'object' && 'code' in e && e.code === 'ENOENT') {
20+
throw new FileDoesNotExistException(path);
21+
}
22+
throw e;
1723
}
1824

1925
const errors: ParseError[] = [];
20-
const content = parse(readFileSync(path, 'utf-8'), errors, { allowTrailingComma: true });
26+
const content = parse(data, errors, { allowTrailingComma: true }) as JsonValue;
2127

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

0 commit comments

Comments
 (0)