forked from UKSOURCE/cms.hailearning.edu.vn
first commit
This commit is contained in:
40
utils/jsonHelper.js
Normal file
40
utils/jsonHelper.js
Normal file
@@ -0,0 +1,40 @@
|
||||
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
|
||||
};
|
||||
Reference in New Issue
Block a user