Skip to content
This repository was archived by the owner on Sep 28, 2020. It is now read-only.

Commit 2aabde7

Browse files
committed
add check before writing file
1 parent d7f003d commit 2aabde7

File tree

1 file changed

+32
-8
lines changed

1 file changed

+32
-8
lines changed

index.js

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,13 @@ var fs = require("fs")
66
var findCacheDir = require("find-cache-dir")
77
var objectHash = require("object-hash")
88
var os = require("os")
9+
var path = require("path")
910

1011
var engines = {}
1112
var rules = {}
1213
var cache = null
1314
var cachePath = null
15+
var cacheFallback = path.join(os.tmpdir(), "eslint-loader", "cache.json")
1416

1517
/**
1618
* linter
@@ -59,13 +61,25 @@ function lint(input, config, webpack) {
5961
res = engine.executeOnText(input, resourcePath, true)
6062

6163
// Save new results in the cache
62-
if (config.cache) {
64+
if (config.cache && cachePath) {
6365
cache[resourcePath] = {
6466
hash: inputMD5,
6567
rules: rulesHash,
6668
res: res,
6769
}
68-
fs.writeFileSync(cachePath, JSON.stringify(cache))
70+
var cacheJson = JSON.stringify(cache)
71+
try {
72+
safeWriteCache(cachePath, cacheJson)
73+
}
74+
catch (e) {
75+
try {
76+
cachePath = cacheFallback
77+
safeWriteCache(cachePath, cacheJson)
78+
}
79+
catch (e) {
80+
cache = false
81+
}
82+
}
6983
}
7084
}
7185

@@ -176,13 +190,13 @@ module.exports = function(input, map) {
176190
// Read the cached information only once and if enable
177191
if (cache === null) {
178192
if (config.cache) {
179-
var thunk = findCacheDir({
180-
name: "eslint-loader",
181-
thunk: true,
182-
create: true,
183-
})
184-
cachePath = thunk("data.json") || os.tmpdir() + "/data.json"
185193
try {
194+
var thunk = findCacheDir({
195+
name: "eslint-loader",
196+
thunk: true,
197+
create: true,
198+
})
199+
cachePath = thunk("data.json")
186200
cache = require(cachePath)
187201
}
188202
catch (e) {
@@ -197,3 +211,13 @@ module.exports = function(input, map) {
197211
lint(input, config, this)
198212
this.callback(null, input, map)
199213
}
214+
215+
function safeWriteCache(cachePath, cacheJson) {
216+
if (fs.existsSync(cachePath)) {
217+
fs.writeFileSync(cachePath, cacheJson)
218+
}
219+
else {
220+
fs.mkdirSync(path.dirname(cachePath))
221+
fs.writeFileSync(cachePath, cacheJson)
222+
}
223+
}

0 commit comments

Comments
 (0)