DEV Community

Manav Misra
Manav Misra

Posted on

My First I/O

learnyounode

From your terminal: learnyounode to open up that menu again, and this time, select the 3rd challenge.

Overview

As per the directions, we are working with I/O - input/output.

Here, that means using the fs module to read some file contents and count the number of lines.

The fs module leverages our Operating System (OS) to, among other things, read/write file contents.

The directions also mention that we will read the file synchronously. This means that we will 'block' the execution of our program from going any further until all of the file contents are read.

Once again, we will receive the name of the file from the command line as part of process.argv.

Start by creating a new file for this program. From the command line: touch my-first-io.js.

require("fs")

We'll destructure readFilesSync from the "fs" _module: const { readFileSync } = require("fs");

Get Info from the CLI

Once again, we are destructuring and 'throwing away_ the first 2 arguments from the command line. The one that we are interested in is the name of the file that we need to read, provided by, process.argv[2], as mentioned in the directions.

Reading and Splitting the File

Now, you can try: console.info(readFileSync(file)).

Run it with learnyounode run my-first-io.js from the command line. This will show us the output of the file provided by learnyounode.

You will see something like: <Buffer. It's pretty useless for this case - it's a 'raw data' buffer πŸ‘ŽπŸ½.

Let's 'decode' it by letting Node know that we want to read this as 'utf-8'. This is a standard for universally converting raw data streams into 'human-readable' characters.

For an interesting bit of trivia, you can watch this:

Now, try: console.info(readFileSync(file, "utf-8")); That's a bit better! πŸ€“ We see some readable words.

Next, we need to split this up into individual lines: console.info(readFileSync(file, "utf-8").split("\n")); That `"\n" tells JS that we want to look for anywhere there is a ''new line' in the text.

If you inspect the output closely, you'll see a ] at the end. There are also ,s between each 'sentence.'

That's because split has converted this string into an array, where each element inside of the array is a separate 'new line.'

Wrapping Up

Our task was to count the number of new lines...we have an array where each element is a new line...

console.info(readFileSync(file, "utf8").split("\n").length - 1);

learnyounode verify my-first-io.js should get it done! πŸ€“

Top comments (0)