Learn you node – Part 1

learn_you_node

Thought of learning node and started searching for tutorials on Google. And I finally ended up with “Learn you Node”, which was actually funny, simply and informative. I immediately dived into it and made my hands dirty.

Here is the best solutions for each of the exercises.

Exercise 1: Hello World

Write a program that prints the text “HELLO WORLD” to the console (stdout).

Solution:

console.log('HELLO WORLD')

It is a tradition to write “Hello World” as the first program, while learning a new programming language.

Exercise 2: BABY STEPS

Write a program that accepts one or more numbers as command-line arguments and prints the sum of those numbers to the console (stdout).

Solution:

var total = 0;
 process.argv.forEach( function(e, i) {
 if (1 < i) {
 total += +e;
 }
 });
 console.log(total);

To receive the arguments passed to the program, use “process.argv”, where “process” is the global object in node with argv property which has the complete command-line. Output of “process,argv” will be

[ 'path/to/your/node.exe',
 'path/to/your/program.js',
 '30',
 '76',
 '28',
 '47',
 '92',
 '59',
 '2',
 '64' ]

Always the first value will be the path of the node file and the second will have the path of the file that is executed currently. To add the arguments sent to the file, start accumulating from the second index. So comes the line

if (1 < i)

Finally, echo the total.

Exercise 3: My First I/O

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

Solution:

var fs = require('fs');
var file = fs.readFileSync(process.argv[2]);
console.log(file.toString().split('\n').length - 1);

Here the real serious programming starts, node has tons of extensions and modules. One such modules is “fs”, which stands for filesystem that comes from the node core library. As learned from the previous example, here we get the name of the file to read from “process.argv[2]”, because first two arguments to argv is occupied by path to node and the program file.

Then to count the number of chars in the file, convert the Buffer object to string and split it into array with newline character and count the words.

Exercise 4: My first async I/O!

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

Solution:

var fs = require('fs');
var file = fs.readFile(process.argv[2], function (err, data) {
 if (!err) {
 console.log(data.toString().split('\n').length - 1);
 }
});

Here use the same “fs” module to read the file but this time with “readFile” method to read the file asynchronously. Since the file fetch happens asynchronously, we cannot expect the content of the file in the next line. Use callback to get it and do as done earlier.

Exercise 5: Filtered LS

Create a program that prints a list of files in a given directory, filtered by the extension of the files. You will be provided a directory name as the first argument to your program (e.g. ‘/path/to/dir/’) and a file extension to filter by as the second argument.

var fs = require('fs');
var path = require('path');
var file = fs.readdir(process.argv[2], function (err, list) {
 if (!err) {
 list.forEach( function(file, i){
 if (path.extname(file) === '.' + process.argv[3]) {
 console.log(file);
 }
 });
 }
});

This program adds spices to our delicious feast. Use “readdir” to get the list of files in a given directory and walk through each file and find its file type with file extension using the “path” module.