Node: Detailed explanation of glob module to obtain file path

introduce

The glob module in Node.js is a module for matching file paths. It can quickly find qualified file or folder paths based on wildcard patterns.

When using the glob module, you need to install the glob module first. You can use npm to install it:

npm install glob --save

Once the installation is complete, you can start using the glob module. Here are some common uses:

  1. glob.sync(pattern[, options])

Synchronously obtains a list of file or folder paths that satisfy a specified wildcard pattern. For example, to get the paths of all .js files, you can write:

const glob = require('glob');
const files = glob.sync('*.js');
console.log(files);
  1. glob(pattern[, options], callback)

Asynchronously obtains a list of file or folder paths that satisfy a specified wildcard pattern. For example, to get the paths of all .js files, you can write:

const glob = require('glob');
glob('*.js', (err, files) => {
  if (err) throw err;
  console.log(files);
});
  1. wildcard pattern

In the glob module, the following wildcards are supported:

  • *Match 0 or more characters
  • ?Match 1 character
  • **Matches all files and zero or more directories

Here are some examples of wildcard patterns:

// 匹配所有.js文件
const files1 = glob.sync('*.js');

// 匹配所有的.js文件和.css文件
const files2 = glob.sync(['*.js', '*.css']);

// 匹配所有的.js文件和.js文件所在的子目录下的.js文件
const files3 = glob.sync('**/*.js');

// 匹配所有目录下的.json文件
const files4 = glob.sync('**/*.json');

The above is some basic introduction and usage of node's glob. In actual development, you can choose different wildcard patterns according to different needs, and use the glob module to match and select file paths, thereby improving development efficiency and reducing repetitive work.

Example

const path = require('path')
const {
    
    
  globSync
} = require('glob')
const jsfiles = globSync('mulu1/**/*.js', {
    
     ignore: 'node_modules/**' })
const jsfiles3 = globSync('mulu1/*.js', {
    
     ignore: 'node_modules/**' })
const jsfiles2 = globSync('mulu1/**/*.{js,css}', {
    
     ignore: 'node_modules/**' })
const jsfiles1 = globSync(['mulu1/**/*.js', 'mulu1/**/*.css'], {
    
     ignore: 'node_modules/**' })
const jsfiles3Path = path.resolve(__dirname, jsfiles3[0])

// [ 'mulu1/1.js' ]
console.log(jsfiles3)
// Users/zhangyu/web/web-all/node-all/glob-test/src/mulu1/1.js
console.log(jsfiles3Path)

Related addresses

https://www.npmjs.com/package/glob
https://github.com/isaacs/node-glob

Guess you like

Origin blog.csdn.net/weixin_43972437/article/details/132849597