UNPKG

nodejs-file-utils

Version:

File Read and Write Apis with Cached content in NodeJs

54 lines (53 loc) 2.1 kB
import { __awaiter, __generator } from "tslib"; import { cloneDeep } from "lodash"; import { normalize } from "path"; var readPromises = {}; var dataMap = {}; export var readFileStore = function (path, reader, force) { if (force === void 0) { force = false; } return __awaiter(void 0, void 0, void 0, function () { var normalizedPath, data, e_1; return __generator(this, function (_a) { switch (_a.label) { case 0: normalizedPath = normalize(path); if (!(!dataMap[normalizedPath] || force)) return [3 /*break*/, 4]; if (!readPromises[normalizedPath] || force) { readPromises[normalizedPath] = reader(normalizedPath); } _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/, readPromises[normalizedPath]]; case 2: data = _a.sent(); dataMap[normalizedPath] = data; return [3 /*break*/, 4]; case 3: e_1 = _a.sent(); delete readPromises[normalizedPath]; throw e_1; case 4: return [2 /*return*/, cloneDeep(dataMap[normalizedPath])]; } }); }); }; export var updateFileStore = function (path, data) { var normalizedPath = normalize(path); dataMap[normalizedPath] = cloneDeep(data); }; export var saveFileStore = function (path, writer) { return __awaiter(void 0, void 0, void 0, function () { var normalizedPath; return __generator(this, function (_a) { switch (_a.label) { case 0: normalizedPath = normalize(path); if (!dataMap[normalizedPath]) return [3 /*break*/, 2]; return [4 /*yield*/, writer(normalizedPath, dataMap[normalizedPath])]; case 1: _a.sent(); _a.label = 2; case 2: return [2 /*return*/]; } }); }); };