zoukankan      html  css  js  c++  java
  • 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进行文件遍历

  • 相关阅读:
    张维迎:你必须知道的10个经济学原理
    艾德莱斯绸:“千年时尚”托起新产业
    Sending forms through JavaScript[form提交 form data]
    Sending form data
    Your first HTML form
    form submission
    <input type="file">
    web storm查看文件结构
    jQuery-File-Upload
    IHttpHandler
  • 原文地址:https://www.cnblogs.com/planetwithpig/p/13986210.html
Copyright © 2011-2022 走看看