FreeCodeCamp and Learning Node: My First I/O

The first real challenge for the Node tutorial is learning I/O from files.  This one was a little more difficult than Baby Steps.  My solution is probably a little clumsy, but I think it’s easy to follow.  Let’s dive in!

So, here’s the learnyounode instructions for My first I/O.

 ## MY FIRST I/O! (Exercise 3 of 13)

  Write a program that uses a single synchronous filesystem operation to read a file and print the number of newlines (\n) it contains to the console (stdout), similar to running cat file | wc -l.

  The full path to the file to read will be provided as the first command-line argument (i.e., process.argv[2]). You do not need to make your own test file.

 ─────────────────────────────────────────────────────────────────────────────

 ## HINTS

  To perform a filesystem operation you are going to need the fs module from the Node core library. To load this kind of module, or any other “global” module, use the following incantation:

  var fs = require(‘fs’)

  Now you have the full fs module available in a variable named fs.

  All synchronous (or blocking) filesystem methods in the fs module end with ‘Sync’. To read a file, you’ll need to use fs.readFileSync(‘/path/to/file’). This method will return a Buffer object containing the complete contents of the file.

  Documentation on the fs module can be found by pointing your browser here:

  file:///home/ubuntu/.nvm/versions/node/v4.4.3/lib/node_modules/learnyounode/node_apidoc/fs.html

  Buffer objects are Node’s way of efficiently representing arbitrary arrays of data, whether it be ascii, binary or some other format. Buffer objects can be converted to strings by simply calling the toString() method on them. e.g. var str = buf.toString().

  Documentation on Buffers can be found by pointing your browser here:

  file:///home/ubuntu/.nvm/versions/node/v4.4.3/lib/node_modules/learnyounode/node_apidoc/buffer.html

  If you’re looking for an easy way to count the number of newlines in a string, recall that a JavaScript String can be .split() into an array of substrings and that ‘\n’ can be used as a delimiter. Note that the test file does not have a newline character (‘\n’) at the end of the last line, so using this method you’ll end up with an array that has one more element than the number of newlines.

First of all, those document addresses are useless.  Those addresses are great if you are on the Node server, but in learnyounode, you’ll get nothing.  You can actually go here to look at the cocumentation, and just search for the term you want:

https://nodejs.org/dist/latest-v6.x/docs/api/

 

For this exercise, in the column on the left, it’s File Server (FS) and Buffer that you want.

Now, if it’s not obvious, Node runs on a server.  That’s why all this stuff looks so arcane compared to HTML, CSS, and yes, writing JavaScript in the browser environment.  Node runs off a command line, too, which adds to the alien feel for Front End Developers.  I have experience with Java and this is still taking some getting used to because I did all my Java development in IDEs.  Let’s work this through.

So, the first hint they give, loading fs, does not take place on the command line – it goes in the file you are writing.  Create a new file (I covered this in the last Node Learning Node post).  Name it whatever you want – I called mine program2.js, because I didn’t want to overwrite program.js, which had my answer to the ‘Baby Steps’ tutorial.

Just copy and paste var fs = require(‘fs’), add a semicolon (hey, we’re writing JavaScript, remember?) and that will be the first line of your program.

 

That was the easy part.

 

Okay, learnyounode is GIVING us the file we need to examine – we don’t need to create one.  They are supplying it to us as a command line argument – remember from the last tutorial that the command line arguments object (process.argv) has ‘node’ as the first element, the file path as the second element, and then third (process.argv[2])and up we have whatever information we need.  So, the file information – the location of it, or path – will be process.argv[2].  Let’s assign that to a variable, and our program now looks like:

var fs = require(‘fs’);

var filename = process.argv[2];

Save early, save often.  You remember that from any word processing classes you took, right?

Next, we’ll start using the other commands given in the hints.  First is fs.readFileSync(‘/path/to/file’).  We saved the path to the file in the variable filename.  The command will return the contents of the file as a Buffer object, so we’re going to save that in another new variable we’ll call bufFile (Buffer File -I’m so original).  Here’s what our file looks like now:

var fs = require(‘fs’);
var filename = process.argv[2];

var bufFile = fs.readFileSync(filename);

We need to convert that Buffer object to a string so we can perform string operations on it.  We’ll do that with toString() and assign it to – you guessed it – yet another new variable, which we’ll call strFile, for String File:

var strFile = bufFile.toString();

Believe it or not, we’re almost there.  Using the split() method (I covered it in this post here) with ‘\n’ – for new line – as the separator, we’ll get an array back that will have each line in the file as a separate element.  We’ll save that in one last variable, called cnt (for count):

var cnt = strFile.split(‘\n’);

Now, as noted in the hints, the last line won’t have a new line at the end of it, and we subtract that line from the total since it doesn’t have one.  We can print it to the console now, and that finishes our program, which now looks like this:

var fs = require(‘fs’);

var filename = process.argv[2];

var bufFile = fs.readFileSync(filename);

var strFile = bufFile.toString();

var cnt = strFile.split(‘\n’);

console.log(cnt.length – 1);

If you’ll remember, I called this one program2.js, so I run it as:

learnyounode verify program2.js

And it comes back as passed!

And there you go.  Let me know if there any questions in the comments!

Advertisements

3 thoughts on “FreeCodeCamp and Learning Node: My First I/O

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s