Node js 3일차
1. JSON.stringfy && JSON.parse
// 키 밸류 다 쌍따움표
JSON.stringfy(test1)
// Object로 만듬 // ㅋ
JSON.parse(test2)
2. JSON Read & Write
const fs = require("fs")
const dataBuffer = fs.readFileSync("test.json") // 숫자로 보인다
const dataJSON = dataBuffet.toString() // 숫자를 문자열로 변환
const data = JSON.parse(dataJSON) // 객체로 바꿔줌으로써 키에 접근 가능
console.log(data)
data.name = "DH_K" // JSON 파일의 이름과 나이를 덮어씀
data.age = 99
const userJSON = JSON.stringfy(data) // 거꾸로 문자열로 바꿔서 덮어씀
fs.writeFileSync("test.json", userJSON)
2.1 JSON 읽고 쓰고 저장
const fs = require("fs")
const addNote = (title, body =>{
const notes = loadNotes()
const duplicateNotes = notes.filter( (note)=> {
// 불러온 notes 중 내가 입력한 제목과 중복 되는것이 있으면
// boolean 반환(true or 1)
return note.title === title
}
if (duplicateNotes.length === 0){
notes.push({
title: title,
body: body,
})
saveNotes(notes)
console.log("notes에 추가되었습니다."
} else {
console.log("제목이 중복되었습니다.")
}
}
const loadNotes = () => {
try{
const dataBuffer = fs.readFileSync("test.json")
const dataJOSN = dataBuffer.toString()
return JSON.parse(dataJSON)
} catch(e) {
return []
}
}
const saveNotes = (notes) => {
const dataJSON = JOSN.stringfy(notes)
fs.writeFileSync("test.json", dataJSON)
}
module.exports = {
addNote: addNote,
//addNote,
}
>>> node app.js add --title="test title" --body="this is body"
2.2 JSON 삭제하기
const chalk = require("chalk")
const removeNote = (title) => {
const notes = loadNotes()
//title과 일치하는 것만 빼고 새로 저장
const notesToKeep = notes.filter( (note)=>{
return note.title !== title
})
saveNotes(notesToKeep)
if (notes.length > notesToKeep.length) {
console.log(chalk.green.inverse("Note removed!"))
saveNotes(notesToKeep)
} else {
console.log(chalk.red.inverse("NO Note found!"))
}
}
module.exports = {
remoteNote,
}