nodechool learnyounode node.js模块FILTER LS练习

下面是nodechool learnyounode模块的练习5

创build一个程序,打印给定目录中的文件列表,并通过文件的扩展名进行过滤。 您将获得一个目录名称作为您的程序的第一个存储库(例如/path/to/dir/ ),并将文件扩展名作为第二个参数进行过滤。

例如,如果您将“txt”作为第二个参数,则需要将列表过滤为仅以.txt结尾的文件。

文件列表应该打印到控制台,每行一个文件,并且必须使用asynchronousI / 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); } }); }); 

当我运行这个我得到了正确的输出,但是当我validation输出使用learnyounode实际结果不符合预期的结果

不知道我哪里错了。 有人可以给我的解决scheme吗?

你的问题只是一个错字。 你正在这样做:

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

,但你应该这样做:

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

其他的事情:他们不考虑这个. 在input中.txt ,所以你必须追加这个在你的variablesext1因为.extname(file)返回的扩展与.

 var ext1 = '.' + process.argv[3]; 

这是官方的解决scheme:

 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) }) }) 

你可以试试这个代码来解决这个练习:

 var fs = require('fs'); function endsWith(str, suffix) { var s = str.slice(str.length - suffix.length - 1); if (s == "." + suffix) return true; else return false; }; fs.readdir(process.argv[2], function (err, list) { if (process.argv[3]) { for (var i = 0; i < list.length; i++) { if (endsWith(list[i], process.argv[3])) console.log(list[i]); } } }); 

这是我想出来的:

 var fs = require('fs'); var filePath = process.argv[2]; var fileType = '.' + process.argv[3]; fs.readdir(filePath, function(err, list) { for(var i=0; i<list.length; i++){ if (list[i].match(fileType)) { console.log(list[i]); } } }); 

下面是我想到的,如果你想要其他解决scheme的问题:

 var fs = require('fs'); var path = process.argv[2]; //first argument var extension = process.argv[3]; //second argument var re = new RegExp("."+extension, "g"); //a regexp that matches every string that begins with a dot and is followed by the extension, ie .txt fs.readdir(path, function callback(err, list){ //read the directory if (!err) { //if no errors occur run next funtion list.forEach(function(val) { //take the list and check every value with the statement below if(re.test(val)) { //if the .test() rexexp-function does not match it will return a false, if it does it will return true console.log(val); //if it matches console log the value } }); } }); 

代码中唯一缺less的是“。”的连接。 之前的文件扩展名types。

var extension ='。'+ process.argv [3];

然后你可以做比较和打印。

多数民众赞成我是如何解决它

 var fs = require('fs'); const path = require("path") var dir = process.argv[2], ext = "."+process.argv[3]; function borer(callback){ fs.readdir(dir,function(err,list){ if(err){ console.log(err) }else{ var row = list.filter((a)=>{ var regexp = new RegExp(ext+"$","ig") if( a.search(regexp) > -1 ){ callback(a) } }) } }) } function print(f){ console.log(f) } borer(print)