import * as fs from 'fs'; import * as json from '@discoveryjs/json-ext'; import { getLogger } from './loggers'; const logger = getLogger('json'); const writeFile = (path: fs.PathLike, obj: object) => new Promise((resolve, reject) => { const renameSync = (oldPath: fs.PathLike, newPath: fs.PathLike) => { try { fs.renameSync(oldPath, newPath); return newPath; } catch (err) { reject(err); } } let backupPath: fs.PathLike; if (fs.statSync(path).size > 0) { backupPath = renameSync(path, `${path}.bak`); } json.stringifyStream(obj) .on('error', err => { logger.error(err); if (fs.existsSync(backupPath)) renameSync(backupPath, path); resolve(false); }) .pipe(fs.createWriteStream(path)) .on('error', err => { reject(err); }) .on('finish', () => { if (fs.existsSync(backupPath)) fs.unlinkSync(`${path}.bak`); resolve(true); }); }); const readFile = (path: fs.PathLike) => new Promise((resolve, reject) => { json.parseChunked( fs.createReadStream(path) .on('error', err => { reject(err); }) ).then(resolve); }); export {writeFile, readFile};