kuaibao/fileOperations.js
2023-08-20 22:26:24 +08:00

30 lines
987 B
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const fs = require("fs");
// 保存题目和答案到txt文件但仅当题目不存在时保存
function saveToFile(data) {
try {
const existingData = readFromFile(); // Read existing data
const newData = { ...existingData, ...data }; // Merge existing and new data
fs.writeFileSync("questions.txt", JSON.stringify(newData), "utf-8");
console.log("Data saved to questions.txt");
} catch (error) {
console.error("Error saving data:", error);
}
}
// 从txt文件中读取题目和答案
function readFromFile(question) {
try {
const data = fs.readFileSync("questions.txt", "utf-8");
const savedData = JSON.parse(data);
if (question) {
return savedData[question] || "Question not found";
} else {
return savedData;
}
} catch (error) {
console.error("Error reading file:", error);
return {};
}
}
module.exports = { saveToFile, readFromFile };