Files
cms.uldp.edu.vn/utils/jsonHelper.js
r2xrzh9q2z-lab d1b931d547 first commit
2026-02-02 11:07:09 +07:00

40 lines
1.1 KiB
JavaScript

const fs = require('fs');
const path = require('path');
/**
* Đọc dữ liệu từ file JSON
* @param {string} fileName - Tên file JSON cần đọc (không cần đuôi .json)
* @returns {Object} - Dữ liệu từ file JSON
*/
function readJsonFile(fileName) {
try {
const filePath = path.join(__dirname, '../data', `${fileName}.json`);
const data = fs.readFileSync(filePath, 'utf8');
return JSON.parse(data);
} catch (error) {
console.error(`Lỗi khi đọc file ${fileName}.json:`, error);
return null;
}
}
/**
* Ghi dữ liệu vào file JSON
* @param {string} fileName - Tên file JSON cần ghi (không cần đuôi .json)
* @param {Object} data - Dữ liệu cần ghi vào file
* @returns {boolean} - Kết quả ghi file
*/
function writeJsonFile(fileName, data) {
try {
const filePath = path.join(__dirname, '../data', `${fileName}.json`);
fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
return true;
} catch (error) {
console.error(`Lỗi khi ghi file ${fileName}.json:`, error);
return false;
}
}
module.exports = {
readJsonFile,
writeJsonFile
};