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