-
Notifications
You must be signed in to change notification settings - Fork 0
/
wordCount.js
76 lines (60 loc) · 2.1 KB
/
wordCount.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
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
const fs = require("fs");
const path = require("path");
const glob = require("glob");
const readingTime = require("reading-time");
const projectRoot = path.join(__dirname);
const logFilePath = path.join(projectRoot, "logfile.json");
glob("**/*.md", { ignore: ["**/node_modules/**", "**/README.md"] }, function (
err,
files
) {
if (err) {
throw new Error(err.message);
}
files.forEach((file) => {
const logFileContent = fs.readFileSync(`${logFilePath}`, "utf8");
const markdownFileContent = fs.readFileSync(`${file}`, "utf8");
const initialWordCount = readingTime(markdownFileContent).words;
const parsedFile = JSON.parse(logFileContent);
const fileName = file.split(".")[0];
const existingFileName = parsedFile[fileName];
if (!existingFileName) {
console.info(
`'${fileName}' seems to be a new file, adding to wordCount.js log file...`
);
const newContent = {
...parsedFile,
[fileName]: {
initialWords: initialWordCount,
},
};
fs.writeFileSync(logFilePath, JSON.stringify(newContent, null, 2));
} else {
const fileObjKeys = Object.keys(existingFileName);
const latestTimestamp = fileObjKeys[fileObjKeys.length - 1];
const currentWords = existingFileName[latestTimestamp].currentWords;
const wordCountExisting =
currentWords != null ? currentWords : existingFileName.initialWords;
const wordCountNew = readingTime(markdownFileContent).words;
const diffTimestamp = new Date().toISOString();
const diffInWords = wordCountNew - wordCountExisting;
if (diffInWords !== 0) {
console.info(`Changes found in '${fileName}', creating diff...`);
const updatingFileWithDiffContent = {
...parsedFile,
[fileName]: {
...existingFileName,
[diffTimestamp]: {
diff: diffInWords,
currentWords: wordCountNew,
},
},
};
fs.writeFileSync(
logFilePath,
JSON.stringify(updatingFileWithDiffContent, null, 2)
);
}
}
});
});