-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelper.js
More file actions
78 lines (66 loc) · 1.96 KB
/
helper.js
File metadata and controls
78 lines (66 loc) · 1.96 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
const fs = require("fs");
const path = require("path");
const xlsx = require("xlsx");
function dirCreator(inputPath) {
let isPresent = fs.existsSync(inputPath);
if (isPresent == false) {
fs.mkdirSync(inputPath);
} else {
console.log(inputPath, "Already Exists");
}
}
function fileHandler(inputPath, dataObj) {
let isFilePresent = fs.existsSync(inputPath);
let arr = [];
if (isFilePresent == false) {
// fileCreater(inputPath, dataObj)
arr.push(dataObj);
excelWriter(inputPath, arr);
} else {
arr = excelReader(inputPath);
arr.push(dataObj);
excelWriter(inputPath, arr);
// fileUpdater(inputPath, dataObj);
}
}
// JSON.stringify -> write
// JSON.parse-> reading
function fileCreater(playerPath, dataObj) {
let arr = [dataObj];
fs.writeFileSync(playerPath, JSON.stringify(arr));
}
function fileUpdater(playerPath, dataObj) {
// file content read
let dataBuffer = fs.readFileSync(playerPath);
// buffer -> JSON
let arr = JSON.parse(dataBuffer);
// JSON entry add
arr.push(dataObj);
//
fs.writeFileSync(playerPath, JSON.stringify(arr));
// console.log("entry updated ", path.basename(playerPath));
}
function excelReader(filePath) {
// file -> read -> workbook
let wb = xlsx.readFile(filePath);
// get a worksheet from a workbook
let excelData = wb.Sheets["sheet1"];
// sheet -> json
let ans = xlsx.utils.sheet_to_json(excelData);
return ans;
}
function excelWriter(filePath, json) {
// console.log(xlsx.readFile(filePath));
// empty workbook
let newWB = xlsx.utils.book_new();
// worksheet
let newWS = xlsx.utils.json_to_sheet(json);
// wb -> put worksheet -> worksheet name -> sheet1
xlsx.utils.book_append_sheet(newWB, newWS, "sheet1");
// worksheet create
xlsx.writeFile(newWB, filePath);
}
module.exports = {
dirCreator: dirCreator,
fileHandler: fileHandler
}