-
Notifications
You must be signed in to change notification settings - Fork 0
/
updateFile.js
42 lines (38 loc) · 1016 Bytes
/
updateFile.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
37
38
39
40
41
42
require("dotenv").config();
const fs = require("fs");
const FILE = __dirname + "/public/json/terms.json";
const ENCODING = "utf8";
/**
* Module for adding new queries to a JSON file of queries
* @module ./updateFile
* @param {String} query Represents the search query
*
*/
module.exports = function updateFile(query) {
fs.readFile(FILE, ENCODING, (err, data) => {
if (err) {
console.log(err);
} else {
let duplicate = false;
const obj = JSON.parse(data);
// Looks for duplicates
obj.terms.forEach((t) => {
if (t.term == query) {
duplicate = true;
}
});
// Checks if the query is already included
if (!duplicate) {
// Adds query to JSON data
obj.terms.push({ term: query });
// Appends JSON to the file
const json = JSON.stringify(obj);
fs.writeFile(FILE, json, ENCODING, (err) => {
if (err) {
console.log(err);
}
});
}
}
});
};