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

Commit 4636c39

Browse files
committed
add check before writing file
1 parent d7f003d commit 4636c39

File tree

2 files changed

+37
-14
lines changed

2 files changed

+37
-14
lines changed

index.js

Lines changed: 36 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,12 @@ 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")
10+
var mkdirp = require("mkdirp")
911

1012
var engines = {}
1113
var rules = {}
1214
var cache = null
13-
var cachePath = null
1415

1516
/**
1617
* linter
@@ -65,7 +66,9 @@ function lint(input, config, webpack) {
6566
rules: rulesHash,
6667
res: res,
6768
}
68-
fs.writeFileSync(cachePath, JSON.stringify(cache))
69+
var cacheJson = JSON.stringify(cache)
70+
var cachePath = getCachePath()
71+
writeCache(cachePath, cacheJson)
6972
}
7073
}
7174

@@ -176,18 +179,7 @@ module.exports = function(input, map) {
176179
// Read the cached information only once and if enable
177180
if (cache === null) {
178181
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"
185-
try {
186-
cache = require(cachePath)
187-
}
188-
catch (e) {
189-
cache = {}
190-
}
182+
cache = readCache(getCachePath())
191183
}
192184
else {
193185
cache = false
@@ -197,3 +189,33 @@ module.exports = function(input, map) {
197189
lint(input, config, this)
198190
this.callback(null, input, map)
199191
}
192+
193+
function writeCache(cachePath, cacheJson) {
194+
mkdirp.sync(path.dirname(cachePath))
195+
fs.writeFileSync(cachePath, cacheJson)
196+
}
197+
198+
function readCache(cachePath) {
199+
try {
200+
return require(cachePath)
201+
}
202+
catch (e) {
203+
return {}
204+
}
205+
}
206+
207+
function getCachePath() {
208+
var cachePath
209+
try {
210+
var thunk = findCacheDir({
211+
name: "eslint-loader",
212+
thunk: true,
213+
create: true,
214+
})
215+
cachePath = thunk("data.json")
216+
}
217+
catch (e) {
218+
cachePath = path.join(os.tmpdir(), "eslint-loader", "cache.json")
219+
}
220+
return cachePath
221+
}

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
"dependencies": {
2222
"find-cache-dir": "^0.1.1",
2323
"loader-utils": "^1.0.2",
24+
"mkdirp": "^0.5.1",
2425
"object-assign": "^4.0.1",
2526
"object-hash": "^1.1.4"
2627
},

0 commit comments

Comments
 (0)