Commit fe74ab22 authored by Milan Wikarski's avatar Milan Wikarski 🎪
Browse files

Initial commit; read, write; readJSON

parents
const fs = require('fs');
/**
* Write some data to a file
*
* @param {string} filename
* @param {*} data
* @param {boolean} [silent = false]
* @returns {Promise.<boolean>} success
*/
function write(filename, data, silent = false) {
return new Promise((resolve, reject) => {
fs.writeFile(filename, data, err => {
if (silent) {
return err ? resolve(false) : resolve(true);
}
return err ? reject(err) : resolve(true);
});
});
}
/**
* Read some data from a file
*
* @param {string} filename
* @param {string} [encoding='utf8']
* @param {boolean} [silent=false]
* @returns {Promise.<string>} data
*/
function read(filename, encoding = 'utf8', silent = false) {
return new Promise((resolve, reject) => {
fs.readFile(filename, encoding, (err, data) => {
if (silent) {
return err ? resolve(null) : resolve(data);
}
return err ? reject(err) : resolve(true);
});
});
}
/**
* Read JSON data from a file
*
* @param {string} filename
* @param {boolean} [silent=false]
* @returns {Promise.<Object>} data
*/
function readJSON(filename, silent = false) {
return new Promise((resolve, reject) => {
read(filename, 'utf8', false)
.then(data => {
try {
return JSON.parse(data);
} catch (err) {
silent ? resolve({}) : reject(err);
}
})
.catch(err => (silent ? resolve({}) : reject(err)));
});
}
module.exports = {
write,
read,
readJSON
};
{
"name": "js-file",
"version": "1.0.0",
"description": "Simple wrapper on top of node.js fs module",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "https://gitlab.creanet.sk/wikarski.milan/js-file.git"
},
"keywords": [
"files"
],
"author": "Milan Wikarski",
"license": "ISC"
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment