Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodeschool learnyounode node.js module FILTER LS exercise

Tags:

node.js

Below is the exercise 5 of nodeschool learnyounode module

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

For example, if you get 'txt' as the second argument then you will need to filter the list to only files that end with .txt.

The list of files should be printed to the console, one file per line and have to use asynchronous I/O.

var fs = require('fs');
var path = require('path');
var mydir = process.argv[2];
var ext1 = process.argv[3]
fs.readdir(mydir, function(err, files){
  if(err){
    throw err
  }
  //console.log(files);
  files.forEach(function(filename){
    var ext = path.extname(filename);
    if(ext == ext1){
      console.log(filename);
    }
  });
});

When i run this i got the correct output, But when i verify output using learnyounode actual result not matching with expected result

Dont know where i went wrong. Can someone give me the solution plz???

like image 954
Psyche Genie Avatar asked Jun 04 '14 16:06

Psyche Genie


2 Answers

Here's the official solution:

var fs = require('fs')
var path = require('path')

fs.readdir(process.argv[2], function (err, list) {
  list.forEach(function (file) {
    if (path.extname(file) === '.' + process.argv[3])
      console.log(file)
  })
})
like image 162
Sharathi RB Avatar answered Oct 13 '22 10:10

Sharathi RB


Your problem is just a typo. You're doing this:

    if(ext == ext){ // you're comparing the same variable
      console.log(filename);
    }

, but you should be doing this:

    if(ext === ext1){ // try to use '==='
      console.log(filename);
    }

Other thing: they're not considering the . of .txt in the input, so you have to append this in your variable ext1 because .extname(file) returns the extention with the .:

var ext1 = '.' + process.argv[3];
like image 2
Rodrigo Medeiros Avatar answered Oct 13 '22 08:10

Rodrigo Medeiros