nodeschool learnyounode node.js module FILTER LS exercise

后端 未结 8 1660
耶瑟儿~
耶瑟儿~ 2021-02-10 05:46

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 w

8条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-10 06:10

    Heres what I came up with, if you want other solutions to problem:

    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, i.e. .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
          }
        });
      }
    });
    

提交回复
热议问题