Try Catch 中的 NodeJS JSON 编写错误

Sri*_*har 0 javascript json node.js

参加 NodeJS 课程,目前正在学习如何为笔记应用程序以 JSON 格式存储数据。如果 .json 文件不存在,则使用 try catch 块来处理错误。第一次执行 catch 块,因为文件是空的,我返回一个空数组并将其存储在 JSON 文件中。当其中有数据时,catch 块也第二次被调用。在讲师视频中,相同的代码起作用并附加数据。我们都在使用 readFileSync 函数。

使用 yargs 进行参数解析。

我在这里错过了什么。

附加代码以及 app.js。

笔记.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
}
Run Code Online (Sandbox Code Playgroud)

应用程序.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)

Run Code Online (Sandbox Code Playgroud)

Mar*_*nde 5

您不是在调用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 []

    }

}
Run Code Online (Sandbox Code Playgroud)

此外,您可以将utf8用作第二个参数fs.readFileSync,并避免toString()调用。

const dataJSON = fs.readFileSync('notes.json', 'utf8')
return JSON.parse(dataJSON)
Run Code Online (Sandbox Code Playgroud)