-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathupdateAnswers.js
More file actions
99 lines (85 loc) · 2.71 KB
/
Copy pathupdateAnswers.js
File metadata and controls
99 lines (85 loc) · 2.71 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/**
* updateAnswers.js
*
* This script generates or updates a JSON file in the `src/_data` directory.
*
* Usage:
* node src/scripts/updateAnswers.js <filename> <n> <answer1> <answer2> ...
*
* Parameters:
*
* <filename> - The name of the JSON file to create or update, without file extension.
* <n> - Number of entries to generate.
* <answer...> - One or more answer strings.
*
* Example:
* node src/scripts/updateAnswers.js example-wordle-answers 3 "answer1" "answer2"
*
* creates or updates `src/_data/example-wordle-answers.json` with 3 new entries of answer1 and answer2.
*
*/
"use strict";
const { v4: uuidv4 } = require("uuid");
const fs = require("fs");
const path = require("path");
const readline = require("readline");
let [filename, nStr, ...answers] = process.argv.slice(2);
const n = parseInt(nStr, 10);
if (!filename) {
console.error("Please provide a filename as the first argument.");
process.exit(1);
}
if (filename && filename.toLowerCase().endsWith(".json")) {
filename = filename.slice(0, -5);
}
if (isNaN(n) || n <= 0) {
console.error("Please provide a valid positive number for n as the second argument.");
process.exit(1);
}
if (answers.length === 0) {
console.error("Please provide at least one answer.");
process.exit(1);
}
const outputDir = path.join(__dirname, "../_data");
const outputFile = path.join(outputDir, `${filename}.json`);
function appendEntries() {
let previousData = {};
if (fs.existsSync(outputFile)) {
try {
const fileContent = fs.readFileSync(outputFile, "utf8").trim();
if (fileContent) {
previousData = JSON.parse(fileContent);
}
} catch (err) {
console.error(`Error reading existing JSON: ${err}`);
process.exit(1);
}
}
// Generate n entries
for (let i = 0; i < n; i++) {
const id = uuidv4();
previousData[id] = {
answers,
createdTimestamp: new Date().toISOString()
};
}
fs.writeFileSync(outputFile, JSON.stringify(previousData, null, 2), "utf8");
console.log(`Added ${n} entries to ${outputFile}`);
}
if (fs.existsSync(outputFile)) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question(`File "${outputFile} already exists, do you want to append to it? (y/n): `, (answer) => {
rl.close();
if (answer.toLowerCase() === "y" || answer.toLowerCase === "yes") {
appendEntries();
} else {
console.log("Please remove the file and try again if you want to make a new file with the entries.");
process.exit(0);
}
});
} else {
appendEntries();
}