json.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import * as fs from 'fs';
  2. import * as json from '@discoveryjs/json-ext';
  3. import { getLogger } from './loggers';
  4. const logger = getLogger('json');
  5. const writeFile = (path: fs.PathLike, obj: object) => new Promise<boolean>((resolve, reject) => {
  6. const renameSync = (oldPath: fs.PathLike, newPath: fs.PathLike) => {
  7. try {
  8. fs.renameSync(oldPath, newPath);
  9. return newPath;
  10. } catch (err) {
  11. reject(err);
  12. }
  13. }
  14. let backupPath: fs.PathLike;
  15. if (fs.statSync(path).size > 0) {
  16. backupPath = renameSync(path, `${path}.bak`);
  17. }
  18. json.stringifyStream(obj)
  19. .on('error', err => { logger.error(err); if (fs.existsSync(backupPath)) renameSync(backupPath, path); resolve(false); })
  20. .pipe(fs.createWriteStream(path))
  21. .on('error', err => { reject(err); })
  22. .on('finish', () => { if (fs.existsSync(backupPath)) fs.unlinkSync(`${path}.bak`); resolve(true); });
  23. });
  24. const readFile = (path: fs.PathLike) => new Promise<any>((resolve, reject) => {
  25. json.parseChunked(
  26. fs.createReadStream(path)
  27. .on('error', err => { reject(err); })
  28. ).then(resolve);
  29. });
  30. export {writeFile, readFile};