Skip to content

Commit

Permalink
add check before writing file
Browse files Browse the repository at this point in the history
  • Loading branch information
viankakrisna authored Feb 27, 2017
1 parent d7f003d commit 0cd7dd0
Showing 1 changed file with 25 additions and 3 deletions.
28 changes: 25 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ var fs = require("fs")
var findCacheDir = require("find-cache-dir")
var objectHash = require("object-hash")
var os = require("os")
var path = require('path')

var engines = {}
var rules = {}
var cache = null
var cachePath = null
var cacheFallback = path.join(os.tmpdir(), 'eslint-loader', 'cache.json')

/**
* linter
Expand Down Expand Up @@ -59,13 +61,23 @@ function lint(input, config, webpack) {
res = engine.executeOnText(input, resourcePath, true)

// Save new results in the cache
if (config.cache) {
if (config.cache && cachePath) {
cache[resourcePath] = {
hash: inputMD5,
rules: rulesHash,
res: res,
}
fs.writeFileSync(cachePath, JSON.stringify(cache))
var cacheJson = JSON.stringify(cacheJson)
try {
safeWriteCache(cachePath)
} catch(e){
try {
cachePath = cacheFallback
safeWriteCache(cachePath)
} catch(e){
cache = false
}
}
}
}

Expand Down Expand Up @@ -181,7 +193,7 @@ module.exports = function(input, map) {
thunk: true,
create: true,
})
cachePath = thunk("data.json") || os.tmpdir() + "/data.json"
cachePath = thunk("data.json") || cacheFallback
try {
cache = require(cachePath)
}
Expand All @@ -197,3 +209,13 @@ module.exports = function(input, map) {
lint(input, config, this)
this.callback(null, input, map)
}


function safeWriteCache(cacheJson){
if (fs.existsSync(cachePath)){
fs.writeFileSync(cachePath, cacheJson)
} else {
fs.mkdirSync(path.dirname(cachePath))
fs.writeFileSync(cachePath, cacheJson)
}
}

0 comments on commit 0cd7dd0

Please sign in to comment.