• node遍历指定目录下所有文件


    需求:执行node脚本遍历文件

    解决:创建demo.js文件,如下

     1 const path = require('path')
     2 const fs = require('fs')
     3 
     4 // ./dist
     5 const basePath = './dist'
     6 
     7 function mapDir(dir, callback, finish) {
     8   fs.readdir(dir, function(err, files) {
     9     if (err) {
    10       console.error(err)
    11       return
    12     }
    13     files.forEach((filename, index) => {
    14       let pathname = path.join(dir, filename)
    15       fs.stat(pathname, (err, stats) => { // 读取文件信息
    16         if (err) {
    17           console.log('获取文件stats失败')
    18           return
    19         }
    20         if (stats.isDirectory()) {
    21           mapDir(pathname, callback, finish)
    22         } else if (stats.isFile()) {
    23           if (['.json', '.less'].includes(path.extname(pathname))) {  // 过滤文件
    24             return
    25           }
    26          // todo something
    27 
    28           fs.readFile(pathname, (err, data) => {
    29             if (err) {
    30               console.error(err)
    31               return
    32             }
    33             callback && callback(data)
    34           })
    35         }
    36       })
    37       if (index === files.length - 1) {
    38         finish && finish()
    39       }
    40     })
    41   })
    42 }
    43 
    44 //执行目录遍历
    45 mapDir(
    46   basePath,
    47   function(file) {
    48     // console.log('TCL: file', file.toString())
    49     // 读取文件后的处理
    50   },
    51   function() {
    52     // console.log('xxx文件目录遍历结束')
    53   }
    54 )
    View Code

    运行 node demo.js进行文件遍历

  • 相关阅读:
    并发包学习(二)-容器学习记录
    初尝微信小程序开发与实践
    记一次全站升级https引发的一系列问题
    Hadoop集群搭建
    es5 的类和继承
    TypeScript 类和继承
    TypeScript 函数
    TypeScript 变量 和 数据类型
    js变量提升与函数提升
    vue 路由监听
  • 原文地址:https://www.cnblogs.com/planetwithpig/p/13986210.html
Copyright © 2020-2023  润新知