路径模式匹配glob -- nodejs常用模块(7)

模块介绍

  • glob模式是指 shell 所使用的简化了的正则表达式。
  • 这里的nodejs的glob模块是,glob模式的javascript实现版本。
  • 每种语言的glob模式会有细小的区别,如js实现的glob模式中支持了**。可以参考这里的文档:https://github.com/isaacs/minimatch
  • 这里的glob模块的功能:返回匹配指定模式的文件名或目录。

帮助文档
http://www.gruntjs.org/article/configuring_tasks.html
https://github.com/isaacs/minimatch
https://github.com/isaacs/node-glob

demo
1.glob的demo

/**
 * 检索某个目录下,符合这些正则表达式的文件列表
 */
var pattern2fileList = function(src, patternList, callback) {
    var pattern = '{'+patternList.join(',')+'}';
    var glob = require("glob");
    glob(pattern, {cwd:src, mark:true}, callback);
}

//demo
var patternList = ['node-glob/**/*.{js,json}','*.js', 'node-glob'];      //{,}中逗号后面不能有空格
var src = '../source';
pattern2fileList(src, patternList, function (err, fileList) {
    if(err) {
        console.log(err);
        return ;
    }
    console.log(fileList);
});

2.minimatch的demo

var minimatch =require('minimatch');
//var result = minimatch('bb/a', '**a');  //false
//var result = minimatch('bb/a', '**/a');  //true
//var result = minimatch('bb/cc/bba', '**a');  //false
var result = minimatch('bb/cc/bba', '**/*a');  //true
console.log(result);

这个东东就是个校验工具。


glob中的参数说明

第一个参数
一个glob模式的式子

第二个参数options常用属性

  • cwd The current working directory in which to search. Defaults to process.cwd().
  • mark Add a / character to directory matches. Note that this requires additional stat calls. default false
  • nocase Perform a case-insensitive match. Note that case-insensitive filesystems will sometimes result in glob returning results that are case-insensitively matched anyway, since readdir and stat will not raise an error.
  • debug Set to enable debug logging in minimatch and glob.


glob模式语法说明

基本语法介绍

  • * 匹配任意数量的字符,但不匹配/
  • ? 匹配单个字符,但不匹配/
  • ** 匹配任意数量的字符,包括/,只要它是路径中唯一的一部分
  • {} 允许使用一个逗号分割的列表或者表达式
  • ! 在模式的开头用于否定一个匹配模式(即排除与模式匹配的信息)
    ps:这里只是列了js版本的glob模式的一些常用语法。

特殊语法**
看了官方文档也没看明白,写了些demo测试了下(如上minimatch的demo),觉得**匹配的内容为路径的父目录或者为空时才会生效。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值