Making Code Stick: Day 2

So I went through the first three lessons of nodeschool‘s learnyounode yesterday, but only got through two today. Still, I’ll be back at it tomorrow.

Lesson 4: MY FIRST ASYNC I/O!

Yesterday, as part of my experimenting with fs.readFileSync, I tried fs.readFile. That made today easier. I also found that because I wrote things down by hand and then blogged them yesterday, I was able to write this without referring to yesterday’s notes or code, though I had to refer to the lesson for the parameter order in the callback function.

You’ll see my notes reflecting two things I had issues with in the first iteration of my code.

Remember: err comes before data in readFile callback params.
Remember: fs = require(‘fs’). Assign the required lib/module to a variable!

The note on assigning the required module to a variable is because I forgot to do that at first. I also forgot that yesterday, so when I gave my code a look before running it for the first time, I caught the error and fixed it, but made a note to myself so I’d hopefully remember.

When I ran the code, it worked the first time.

My code:

Lesson 4: FILTERED LS

The idea here is to take a path and an extension as the arguments, read the list of files at the path and output a list of all that have the specified extension. This introduces the path module and the extname method to quickly give you the extension of the file you feed it. Many of the functions could be done with splitting and/or regexes, but one of the reasons for using libs/modules is so you don’t have to do all these things by hand. My notes…

path.extname(p) only takes one argument.
fs.readdir(path, callback(err, list){}) – content is second param in callback again – also has readdirSync.

Here’s my code.

Two things I noticed about the official solution:

  1. They add the period during the check, while I add it when I grab the arg. I think mine is more efficient because it only does the concatenation operation once, while theirs does it on every check.
  2.  

  3. They use list.forEach(function(file){...}, while I use for(var i in list){}. I looked up articles on the comparative performance, and the for loop is 3x faster than the forEach loop. On the other hand, if I was really tuning for perf, I’d probably assign the length of list to a variable before composing the loop, then use that variable as the limit so there’s no chance of calculating the array length with each iteration of the loop.

Leave a Reply

Your email address will not be published. Required fields are marked *

*