From 5f36cd9f379fd511b298990ffd7cb74d6eff9a55 Mon Sep 17 00:00:00 2001 From: Hiroki Osame Date: Fri, 13 May 2022 12:15:00 -0400 Subject: [PATCH] fix: safe json file reading --- src/esbuild/cache.ts | 43 ++++++++++++++++++------------------ src/utils/json-parse-safe.ts | 7 ------ src/utils/read-json-file.ts | 8 +++++++ 3 files changed, 30 insertions(+), 28 deletions(-) delete mode 100644 src/utils/json-parse-safe.ts create mode 100644 src/utils/read-json-file.ts diff --git a/src/esbuild/cache.ts b/src/esbuild/cache.ts index 23359c0..402e8aa 100644 --- a/src/esbuild/cache.ts +++ b/src/esbuild/cache.ts @@ -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); @@ -52,29 +52,30 @@ class FileCache extends Map { } 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(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) { diff --git a/src/utils/json-parse-safe.ts b/src/utils/json-parse-safe.ts deleted file mode 100644 index 7b6c911..0000000 --- a/src/utils/json-parse-safe.ts +++ /dev/null @@ -1,7 +0,0 @@ -export function jsonParseSafe(string: string) { - try { - return JSON.parse(string); - } catch { - return null; - } -} diff --git a/src/utils/read-json-file.ts b/src/utils/read-json-file.ts new file mode 100644 index 0000000..14ca443 --- /dev/null +++ b/src/utils/read-json-file.ts @@ -0,0 +1,8 @@ +import fs from 'fs'; + +export function readJsonFile(filePath: string) { + try { + const jsonString = fs.readFileSync(filePath, 'utf8'); + return JSON.parse(jsonString) as JsonType; + } catch {} +}