From 4636c3901c8a42684f4bbac67c6c7a083e5ff5f3 Mon Sep 17 00:00:00 2001 From: Ade Viankakrisna Fadlil Date: Mon, 27 Feb 2017 23:24:13 +0700 Subject: [PATCH] add check before writing file --- index.js | 50 ++++++++++++++++++++++++++++++++++++-------------- package.json | 1 + 2 files changed, 37 insertions(+), 14 deletions(-) diff --git a/index.js b/index.js index e47758a..6e3b4c3 100644 --- a/index.js +++ b/index.js @@ -6,11 +6,12 @@ var fs = require("fs") var findCacheDir = require("find-cache-dir") var objectHash = require("object-hash") var os = require("os") +var path = require("path") +var mkdirp = require("mkdirp") var engines = {} var rules = {} var cache = null -var cachePath = null /** * linter @@ -65,7 +66,9 @@ function lint(input, config, webpack) { rules: rulesHash, res: res, } - fs.writeFileSync(cachePath, JSON.stringify(cache)) + var cacheJson = JSON.stringify(cache) + var cachePath = getCachePath() + writeCache(cachePath, cacheJson) } } @@ -176,18 +179,7 @@ module.exports = function(input, map) { // Read the cached information only once and if enable if (cache === null) { if (config.cache) { - var thunk = findCacheDir({ - name: "eslint-loader", - thunk: true, - create: true, - }) - cachePath = thunk("data.json") || os.tmpdir() + "/data.json" - try { - cache = require(cachePath) - } - catch (e) { - cache = {} - } + cache = readCache(getCachePath()) } else { cache = false @@ -197,3 +189,33 @@ module.exports = function(input, map) { lint(input, config, this) this.callback(null, input, map) } + +function writeCache(cachePath, cacheJson) { + mkdirp.sync(path.dirname(cachePath)) + fs.writeFileSync(cachePath, cacheJson) +} + +function readCache(cachePath) { + try { + return require(cachePath) + } + catch (e) { + return {} + } +} + +function getCachePath() { + var cachePath + try { + var thunk = findCacheDir({ + name: "eslint-loader", + thunk: true, + create: true, + }) + cachePath = thunk("data.json") + } + catch (e) { + cachePath = path.join(os.tmpdir(), "eslint-loader", "cache.json") + } + return cachePath +} \ No newline at end of file diff --git a/package.json b/package.json index dad56f6..2446ded 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,7 @@ "dependencies": { "find-cache-dir": "^0.1.1", "loader-utils": "^1.0.2", + "mkdirp": "^0.5.1", "object-assign": "^4.0.1", "object-hash": "^1.1.4" },