nodejs 工具库推荐(文件读取node-glob)

2,379 阅读1分钟

文件的操作

1.文件读取:node-glob

使用shell的模式匹配文件。

相比fs的原生的读取文件的优势:

  1. 便捷的遍历文件树
  2. 极易上手

示例:

  1. 安装
npm i glob
  1. 异步写法
const glob = require("glob")

glob('./source/**', (err,ctx) =>{
  console.log("err", err); // err null
  console.log("ctx", ctx); // ctx [ './source', './source/main.js' ]
})
  1. 同步写法
const glob = require("glob")

const filePath = glob.sync('./source/**'); // [ './source', './source/main.js' ]

tip: 输入的路径应该以执行nodejs代码的路径作为定位的。

匹配规则示例:

文件结构:
- source
  - folder1
    - file1.json
  - folder2
  - file.json

匹配:
"source/*"       // source下面的第一层的所有文件和文件夹
// [ './source/file.json', './source/folder1', './source/folder2' ]

"source/**"      // source文件夹下面的所有文件和文件夹
// ['./source', './source/file.json', './source/folder1', './source/folder1/file1.json','./source/folder2']

"source/**/*.json" // source文件夹下面的所有json文件
// [ './source/file.json', './source/folder1/file1.json' ]

链接:node-glob