nodeschool learnyounode node.js module FILTER LS exercise

后端 未结 8 1290
面向向阳花
面向向阳花 2021-02-10 05:38

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:23

    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];
    
    0 讨论(0)
  • 2021-02-10 06:24

    thats how i solved it

    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)
    
    0 讨论(0)
提交回复
热议问题