|
| 1 | +const fs = require('fs'); |
| 2 | +const util = require('util'); |
| 3 | + |
| 4 | +// Promise version of fs.readFile |
| 5 | +const readFromFile = util.promisify(fs.readFile); |
| 6 | +/** |
| 7 | + * Function to write data to the JSON file given a destination and some content |
| 8 | + * @param {string} destination The file you want to write to. |
| 9 | + * @param {object} content The content you want to write to the file. |
| 10 | + * @returns {void} Nothing |
| 11 | + */ |
| 12 | +const writeToFile = (destination,content) => |
| 13 | + fs.writeFile(destination,JSON.stringify(content,null,4),(err) => |
| 14 | + err ? console.error(err) : console.info(`\nData written to ${destination}`) |
| 15 | + ); |
| 16 | +/** |
| 17 | + * Function to read data from a given a file and append some content |
| 18 | + * @param {object} content The content you want to append to the file. |
| 19 | + * @param {string} file The path to the file you want to save to. |
| 20 | + * @returns {void} Nothing |
| 21 | + */ |
| 22 | +const readAndAppend = (content,file) => |
| 23 | +{ |
| 24 | + fs.readFile(file,'utf8',(err,data) => |
| 25 | + { |
| 26 | + if (err) { |
| 27 | + console.error(err); |
| 28 | + } else { |
| 29 | + const parsedData = JSON.parse(data); |
| 30 | + parsedData.push(content); |
| 31 | + writeToFile(file,parsedData); |
| 32 | + } |
| 33 | + }); |
| 34 | +}; |
| 35 | + |
| 36 | +module.exports = { readFromFile,writeToFile,readAndAppend }; |
0 commit comments