Sriram Sridhar
Sriram Sridhar

Reputation: 101

NodeJS JSON writing bug in Try Catch

Taking a course on NodeJS and currently learning about storing data in JSON format for a note taking app. Used a try catch block to handle errors if the .json file didn't exist. First time the catch block executes because the file is empty and the I return an empty array and store it in the JSON file. Second time also the catch block gets called when there is data in it. In the instructors video the same code works and appends the data. We are both using readFileSync function.

Using yargs for argument parsing.

What am I missing here.

Attaching code as well as 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)

Upvotes: 0

Views: 112

Answers (1)

Marcos Casagrande
Marcos Casagrande

Reputation: 40404

You're not calling toString, just accessing the property. Change .toString to .toString()

const loadNotes = function(){

    try{
        const dataBuffer = fs.readFileSync('notes.json')
        const dataJSON = dataBuffer.toString() // changed this
        return JSON.parse(dataJSON)
    } catch(e){
        return []

    }

}

Also, you can use utf8 as second argument to fs.readFileSync, and avoid toString() call.

const dataJSON = fs.readFileSync('notes.json', 'utf8')
return JSON.parse(dataJSON)

Upvotes: 5

Related Questions