|-data
| |- users.json
|- routes
|- app.js
users.json
만들기{
"test": {
"pw": "asdf",
"name": "관리자"
}
}
"test"
가 id(key) "pw", "name"
은 data가 된다
console.log(user["test"].pw); // "asdf"
console.log(user["mike"]); // undefined
fs.readFile(__dirname + `/../data/users.json`, (err, data) => {
if(err)
console.log(err);
const users= JSON.parse(data);
console.log(users);
});
util.js
에 모듈화 해서 로그인 실습하기/* LOAD DATA */
const loadData = (fileName, afterFunc) => {
fs.readFile(__dirname + `/../data/${fileName}`, (err, data) => {
if(err)
console.log(err)
const json = JSON.parse(data)
afterFunc(json);
});
}
/* SAVE DATA */
const saveData = (fileName, newData, afterFunc=()=>{}) => {
fs.writeFile(__dirname + `/../data/${fileName}`, JSON.stringify(newData, null, '\\t'), (err, data) => {
if(err)
console.log(err)
afterFunc();
})
}
module.exports = {loadData, saveData}
로그인으로 활용하기
router.get('/login', (req, res) => {
const {id, pw} = req.query;
loadData(Fname.users, (json) => {
const users = json;
const result = { success: false };
if(!users[id])
result.err = "😢 Check Your ID";
else if(users[id].pw !== pw)
result.err = "😢 Check Your PW";
else
result.success = true;
res.json(result);
});
})