json.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.readFile = exports.writeFile = void 0;
  4. const fs = require("fs");
  5. const json = require("@discoveryjs/json-ext");
  6. const loggers_1 = require("./loggers");
  7. const logger = (0, loggers_1.getLogger)('json');
  8. const writeFile = (path, obj) => new Promise((resolve, reject) => {
  9. const renameSync = (oldPath, newPath) => {
  10. try {
  11. fs.renameSync(oldPath, newPath);
  12. return newPath;
  13. }
  14. catch (err) {
  15. reject(err);
  16. }
  17. };
  18. let backupPath;
  19. if (fs.statSync(path).size > 0) {
  20. backupPath = renameSync(path, `${path}.bak`);
  21. }
  22. json.stringifyStream(obj)
  23. .on('error', err => { logger.error(err); if (fs.existsSync(backupPath))
  24. renameSync(backupPath, path); resolve(false); })
  25. .pipe(fs.createWriteStream(path))
  26. .on('error', err => { reject(err); })
  27. .on('finish', () => { if (fs.existsSync(backupPath))
  28. fs.unlinkSync(`${path}.bak`); resolve(true); });
  29. });
  30. exports.writeFile = writeFile;
  31. const readFile = (path) => new Promise((resolve, reject) => {
  32. json.parseChunked(fs.createReadStream(path)
  33. .on('error', err => { reject(err); })).then(resolve);
  34. });
  35. exports.readFile = readFile;