Saving Notes to a JSON file: Day Six of "The Complete Node.js Developer Course"

in #javascript7 years ago

photo5005946566204303301 Cropped.jpg

After a few days off, I'm resuming my Node.js studies

Back at it. I was planning on programming and writing about it both Monday and Tuesday, but life happened. What I've learned in this process of learning programming is that daily practice is really important. If you miss a couple days, just get back to it. Don't let a few days turn into a week!

Previously

Saving notes to a JSON file

This section 16. Adding and Saving Notes was all about using the addNote function to take in parameters from the command line for a note title and body and then write them to a notes-data.json file.

We did require the fs built-in module from node with:

const fs = require('fs');

Here's the completed code from the addNote function for this section:

var addNote = (title, body) => {
  var notes = [];
  var note = {
    title,
    body
  }

  try {
    var notesString = fs.readFileSync('notes-data.json')
    notes = JSON.parse(notesString)
  } catch (e) {

  }

  var duplicateNotes = notes.filter((note) => note.title === title)

  if (duplicateNotes.length === 0) {
    notes.push(note);
    fs.writeFileSync('notes-data.json', JSON.stringify(notes))
  }
}

Learning new things

There were a few things that I hadn't encountered before. I hadn't used the "try, catch" logic before to deal with errors. Essentially, the code in "try" will be tried. If there are no errors, then the code will run. If there are errors, like the "notes-data.json" file not existing yet, then that bit of code won't run.

Also, I hadn't used the .filter method. I'm still not entirely clear on how this bit of code works:

var duplicateNotes = notes.filter((note) => note.title === title)

But I understand what it does. It checks to see if the incoming note has the same title as any of the previously saved notes. If it does have the same title, it adds that to an array called duplicateNotes. The next bit of code checks to see if the length of that array is zero. If it is zero, then the incoming note title isn't the same as any of the other previously saved notes. That checked, the note is written to the file. If the array duplicateNotes has a length of anything other than zero, the incoming note is not written to the file.

Progress!

I'm feeling like I want to be making faster progress, but it's undeniable that I am making progress. I have to remind myself that I can't learn complex skills in a day. It takes time.

It has also been good for me to write these posts. By writing an explanation of what I've learned, I confirm to myself that I understand it (or at least a good deal of it).

Other node.js learning

I was very happy to attend a local meetup this evening where the topic was REST APIs with node.js and express. I was happy that I understood a good deal of what was presented. Also glad that the code presented in the talk was saved to a github repository that I can go back to and reference when I start to build my own apps.

Thanks for reading!

--- @matthewdavid

Sort:  

Awesome share Matt! (or do you go by Matthew?)

var duplicateNotes = notes.filter((note) => note.title === title)

Your explanation of how it works is correct. Since notes contains a list of javascript object like

{
  title: 'Some String'
  body: 'whatever'
}

It basically is "filter"-ing out from your array of objects that matches those conditions... in this case "title".

The ((note)) part is arbitrary. You could have put apple and do the comparison like apple.title === title.

It is not related to the note variable you created initially in the addNote function. Hope that helps :)

Thanks, that does help. I appreciate it.

I do go by Matthew.

I am not to up on JavaScript lambda but is this valid, as in no brackets around the param. I know C# only requires the brackets when more than one argument into the lambda.

var duplicateNotes = notes.filter(note => note.title === title)

As you can see, I am a clean code junkie lol The less characters while remaining readable is always better :)

Again excellent work I can't wait for the next post

Thanks! I'll keep pushing myself to code and write about it. Thanks for the encouragement.

Good to see nice consistent code layout :) Makes it easier to digest code when it feels familiar.

Eating exceptions like this is not a good idea, you never know if it was failure in the reading or something else.

Not sure the best solution for this bit, could even generate a note with the failure info?

It is the sort of thing that comes back later to bite you.

hth

Woz

try {
    var notesString = fs.readFileSync('notes-data.json')
    notes = JSON.parse(notesString)
  } catch (e) {

  }

I see what you are saying with this and I thought about it when going through this exercise. This section in the course left the code like this, but it makes sense to give some feedback if an error occurred. I think the next section will be refactoring this bit of code so that the logic can be reused by other functions. We'll see when I get there.

Will be interesting to see what they propose is the correct way after the refactor :)

One other thing I noticed is there is no try/catch around the writing of the file so if that fails for whatever reason it will bubble up while the read is caught. Was that intentional?

Eating exceptions like this is not a good idea, you never know if it was failure in the reading or something else.

I agree with this. Maybe you can try making it fail on purpose (trying to open a file that doesn't exist for example) and then console.log(e) so you can see what is returned. Normally when I catch errors I do console.log(e.stack), and it gives enough explanation of what happened.

Also, I learned how to use .filter() with your post and the further explanation that @kkomaz wrote.

Coin Marketplace

STEEM 0.20
TRX 0.13
JST 0.030
BTC 67271.13
ETH 3515.41
USDT 1.00
SBD 2.70