40 lines
1.0 KiB
JavaScript
40 lines
1.0 KiB
JavaScript
const fs = require('fs');
|
|
const path = require('path');
|
|
const mkdirp = require('mkdirp');
|
|
|
|
const CONFIG_FILENAME = 'pkgcomp.json';
|
|
|
|
exports.read = (fileRoot, ident) => {
|
|
const stats = fs.statSync(fileRoot);
|
|
const filePath = path.join(fileRoot, CONFIG_FILENAME);
|
|
|
|
// throw if pointing to a file
|
|
if (stats.isFile()) throw new Error(`getData expects a directory, got a file; ${fileRoot}`);
|
|
|
|
// create file if it's missing
|
|
if (!stats.isDirectory()) {
|
|
mkdirp.sync(fileRoot);
|
|
}
|
|
|
|
try {
|
|
const data = JSON.parse(fs.readFileSync(filePath));
|
|
return data[ident] || {};
|
|
} catch (err) {
|
|
if (err.code === 'ENOENT') {
|
|
fs.writeFileSync(filePath, JSON.stringify({}));
|
|
return {};
|
|
}
|
|
throw err;
|
|
}
|
|
};
|
|
|
|
exports.write = (fileRoot, ident, payload) => {
|
|
const filePath = path.join(fileRoot, CONFIG_FILENAME);
|
|
const existingCache = JSON.parse(fs.readFileSync(filePath));
|
|
|
|
// update the cache
|
|
existingCache[ident] = payload;
|
|
|
|
fs.writeFileSync(filePath, JSON.stringify(existingCache));
|
|
};
|