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???
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)
})
})
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With