Skip to content
This repository has been archived by the owner on Oct 18, 2023. It is now read-only.

fix: safe json file reading #1

Merged
merged 1 commit into from
May 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 22 additions & 21 deletions src/esbuild/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import fs from 'fs';
import path from 'path';
import os from 'os';
import type { TransformResult } from 'esbuild';
import { jsonParseSafe } from '../utils/json-parse-safe';
import { readJsonFile } from '../utils/read-json-file';

const getTime = () => Math.floor(Date.now() / 1e8);

Expand Down Expand Up @@ -52,29 +52,30 @@ class FileCache extends Map<string, TransformResult> {
}

const diskCacheHit = this.cacheFiles.find(cache => cache.key === key);
if (diskCacheHit) {
const cacheFilePath = path.join(this.cacheDirectory, diskCacheHit.fileName);
const cacheFile = fs.readFileSync(cacheFilePath, 'utf8');
const cachedResult: TransformResult = jsonParseSafe(cacheFile);

if (!cachedResult) {
// Remove broken cache file
fs.promises.unlink(cacheFilePath).then(
() => {
const index = this.cacheFiles.indexOf(diskCacheHit);
this.cacheFiles.splice(index, 1);
},
// eslint-disable-next-line @typescript-eslint/no-empty-function
() => {},
);
return;
}
if (!diskCacheHit) {
return;
}

// Load it into memory
super.set(key, cachedResult);
const cacheFilePath = path.join(this.cacheDirectory, diskCacheHit.fileName);
const cachedResult = readJsonFile<TransformResult>(cacheFilePath);

return cachedResult;
if (!cachedResult) {
// Remove broken cache file
fs.promises.unlink(cacheFilePath).then(
() => {
const index = this.cacheFiles.indexOf(diskCacheHit);
this.cacheFiles.splice(index, 1);
},
// eslint-disable-next-line @typescript-eslint/no-empty-function
() => {},
);
return;
}

// Load it into memory
super.set(key, cachedResult);

return cachedResult;
}

set(key: string, value: TransformResult) {
Expand Down
7 changes: 0 additions & 7 deletions src/utils/json-parse-safe.ts

This file was deleted.

8 changes: 8 additions & 0 deletions src/utils/read-json-file.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import fs from 'fs';

export function readJsonFile<JsonType>(filePath: string) {
try {
const jsonString = fs.readFileSync(filePath, 'utf8');
return JSON.parse(jsonString) as JsonType;
} catch {}
}