index.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. const fs = require('fs');
  4. const path = require('path');
  5. const _memo = {
  6. _pid: process.pid
  7. };
  8. async function getMemo(config) {
  9. const options = getOptions(config);
  10. try {
  11. const memo = JSON.parse(await fs.promises.readFile(options.file, "utf-8")) || {};
  12. if (!memo._pid) {
  13. throw new Error("Memo lacks _pid");
  14. }
  15. if (memo._pid === _memo._pid || !isAlive(memo.pid)) {
  16. Object.assign(_memo, memo);
  17. _memo._pid = process.pid;
  18. }
  19. } catch (e) {
  20. }
  21. return _memo;
  22. }
  23. async function setMemo(memo, config) {
  24. const options = getOptions(config);
  25. Object.assign(_memo, memo);
  26. _memo._pid = process.pid;
  27. try {
  28. await fs.promises.mkdir(options.dir);
  29. } catch (e) {
  30. }
  31. try {
  32. await fs.promises.writeFile(options.file, JSON.stringify(_memo), "utf-8");
  33. } catch (e) {
  34. }
  35. }
  36. function getOptions(config) {
  37. const options = {...config};
  38. options.name = options.name || "default";
  39. options.dir = options.dir || path.resolve(process.cwd(), "node_modules/.cache/fs-memo");
  40. options.file = options.file || path.resolve(options.dir, options.name + ".json");
  41. return options;
  42. }
  43. function isAlive(pid) {
  44. try {
  45. process.kill(pid, 0);
  46. return true;
  47. } catch (e) {
  48. return e.code === "EPERM";
  49. }
  50. }
  51. exports.getMemo = getMemo;
  52. exports.setMemo = setMemo;