json是覆盖当我使用fs.writefilesync



我想添加一些东西到我的儿子文件,但当我试图添加它只是覆盖我的儿子文件谁能帮助我这个

const fs = require('fs')
const chalk = require('chalk')
const getNotes = function(){
return 'Your notes....'
}
// add note function 
const addNote = function (title, body) {
const notes = loadNotes()
const duplicateNotes = notes.filter(function (note) {
return note.title === title
})
if (duplicateNotes.length === 0) {
notes.push({
title: title,
body: body
})
saveNotes(notes)
console.log(chalk.green.inverse('New note added!'))
} else {
console.log(chalk.red.inverse('Note title taken!'))
}
}
const saveNotes = function(notes){
const dataJSON = JSON.stringify(notes)
fs.writeFileSync('notes.json', dataJSON)
}
const loadNotes = function(){
try{
const dataBuffer = fs.readFileSync(notes.json)
const dataJSON = dataBuffer.toString();
return JSON.parse(dataJSON)
}catch (e){
return []
}
} 

module.exports = {
getNotes: getNotes,
addNote: addNote,
}

当我运行node app.js添加——title="list"——身体="apple"然后我添加另一个不同的标题和正文它会覆盖——title="list"——body="apple为什么会这样?

你好像忘记加引号了:

const dataBuffer = fs.readFileSync(notes.json)

应该

const dataBuffer = fs.readFileSync('notes.json')

最新更新