Skip to content

Instantly share code, notes, and snippets.

@emersonbroga
Created September 30, 2021 02:48
Show Gist options
  • Save emersonbroga/0502ae69db79d65320b887352ca553fd to your computer and use it in GitHub Desktop.
Save emersonbroga/0502ae69db79d65320b887352ca553fd to your computer and use it in GitHub Desktop.
Json Helper
const fs = require('fs');
const JSONWrite = (filePath, data, encoding = 'utf-8') => {
const promiseCallback = (resolve, reject) => {
fs.writeFile(filePath, JSON.stringify(data, null, 2), encoding, (err) => {
if (err) {
reject(err);
return;
}
resolve(true);
});
};
return new Promise(promiseCallback);
};
const JSONRead = (filePath, encoding = 'utf-8') => {
const promiseCallback = (resolve, reject) => {
fs.readFile(filePath, encoding, (err, data) => {
if (err) {
reject(err);
return;
}
try {
const object = JSON.parse(data);
resolve(object);
} catch (e) {
reject(e);
}
});
};
return new Promise(promiseCallback);
};
const JSONUpdate = (filePath, newData, encoding = 'utf-8') => {
const promiseCallback = async (resolve, reject) => {
try {
const data = await JSONRead(filePath, encoding);
const result = { ...data, ...newData };
await JSONWrite(filePath, result, encoding);
resolve(result);
} catch (e) {
reject(e);
}
};
return new Promise(promiseCallback);
};
const JSONDelete = (filePath) => {
const promiseCallback = (resolve, reject) => {
fs.unlink(filePath, (err) => {
if (err) {
reject(err);
return;
}
resolve(true);
});
};
return new Promise(promiseCallback);
};
module.exports = { JSONRead, JSONWrite, JSONUpdate, JSONDelete };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment