正在学习 NodeJS 类(class),目前正在学习如何为笔记应用程序以 JSON 格式存储数据。如果 .json 文件不存在,则使用 try catch block 来处理错误。第一次执行 catch block 是因为文件为空,我返回一个空数组并将其存储在 JSON 文件中。第二次,当其中有数据时,catch block 也会被调用。在讲师视频中,相同的代码可以运行并附加数据。我们都使用 readFileSync 函数。
使用 yargs 进行参数解析。
我在这里缺少什么。
附加代码以及 app.js。
Notes.js
const getNotes = function () {
return 'Your notes...'
}
const addNote = function(title, body){
const notes = loadNotes()
notes.push({
title: title,
body: body
})
saveNotes(notes)
}
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
}
App.js
const yargs = require('yargs')
const notes = require('./notes.js')
const command = process.argv[2]
yargs.version('1.1.0')
yargs.command({
command: 'add',
describe: 'Add a new note',
builder: {
title: {
describe: 'Note title',
demandOption: true,
type: 'string'
},
body: {
describe: 'Note body',
demandOption: true,
type: 'string'
}
},
handler: function(argv){
notes.addNote(argv.title, argv.body)
}
})
yargs.command({
command: 'list',
describe: 'Lists all notes',
handler: function(){
console.log('Listing notes')
}
})
yargs.command({
command: 'read',
describe: 'Reads all notes',
handler: function(){
console.log('Reading notes')
}
})
yargs.command({
command: 'remove',
describe: 'Remove a note',
handler: function(){
console.log('Removing note')
}
})
yargs.parse()
//console.log(yargs.argv)
最佳答案
您没有调用toString
,只是访问该属性。将 .toString
更改为 .toString()
const loadNotes = function(){
try{
const dataBuffer = fs.readFileSync('notes.json')
const dataJSON = dataBuffer.toString() // changed this
return JSON.parse(dataJSON)
} catch(e){
return []
}
}
此外,您还可以使用 utf8
作为 fs.readFileSync
的第二个参数,并避免 toString()
调用。
const dataJSON = fs.readFileSync('notes.json', 'utf8')
return JSON.parse(dataJSON)
关于javascript - Try Catch 中的 NodeJS JSON 写入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59338913/