nodeschool.io 5

~~ FILTERED LS ~~

Create a program that prints a list of files in a given directory,
filtered by the extension of the files. You will be provided a
directory name as the first argument 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.
You must use asynchronous I/O.

----------------------------------------------------------------------
HINTS:

The `fs.readdir()` method takes a pathname as its first argument and a
callback as its second. The callback signature is:

function (err, list) { ... }

where `list` is an array of filename strings.

Documentation on the `fs` module can be found by pointing your browser
here:
C:\Users\dzhang\AppData\Roaming\npm\node_modules\learnyounode\node_api
tml

You may also find the standard JavaScript `RegExp` class helpful here.

我写的:

var fs = require('fs');
var patt1=new RegExp("\.dat");
var fliter = fs.readdir(process.argv[2],function(err,list){
    for(var i = 0 ; i < list.length ; i++){

        if(list[i].split(".").length > 1){
            if(patt1.exec(list[i])){
                console.log(list[i]);
            }
        }
    }
})

网站的答案:

  var fs = require('fs')
  var regex = new RegExp('\\.' + process.argv[3] + '$')

  fs.readdir(process.argv[2], function (err, list) {
    list.forEach(function (file) {
      if (regex.test(file))
        console.log(file)
    })
  })

 

转载于:https://www.cnblogs.com/della/p/3425623.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值