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

Commit

Permalink
fix: safe json file reading (#1)
Browse files Browse the repository at this point in the history
  • Loading branch information
privatenumber authored May 13, 2022
1 parent 3bbb1b4 commit 1bda96a
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 28 deletions.
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 {}
}

0 comments on commit 1bda96a

Please sign in to comment.