zoukankan      html  css  js  c++  java
  • node遍历给定目录下特定文件,内容合并到一个文件


    遍历目录用了fs.readdir这个异步方法,得到当前目录下所有的文件和目录的一个数组。
    然后判断:

    if文件,并且后缀符合设定的规则(本文例子是符合后缀ts,js)直接用同步方法写入,

    if目录,继续调用这个方法递归。

    const fs = require('fs');
    const path = require('path');
    /*
    需要遍历的目录
    这里写了绝对路径
    */
    const sourceDir = '/Users/xiaochong/workspace/game/phonics2/assets';
    /*
    合并后的目标文件路径
    */
    const targetFile = './lp2.txt';
    
    function getDirFilePathArr(dir) {
        fs.readdir(dir,(err,fileArrLike)=>{
            if(err) {
                console.log(err);
                return;
            }
            fileArrLike.forEach((filename)=>{
                fs.stat(path.join(dir,filename),(err, stats)=> {
                    if (err) throw err;
                    if(stats.isFile()) {
                        if (path.extname(filename) === '.ts' ||path.extname(filename) === '.js') {
                            let filePath = path.join(dir,filename);
                            console.log(filePath);
                            //同步方法:往目标文件targetFile里写入
                            appendContentSync(targetFile,filePath)
                        }
                    }else{//目录,递归
                        getDirFilePathArr(path.join(dir,filename));
                    }
                })
            })
        })
    }
    
    function appendContentSync(targetFile,file){
        let content = fs.readFileSync(file, 'utf-8');
        fs.appendFileSync(targetFile, content)
    }
    getDirFilePathArr(sourceDir);
    

      

      

  • 相关阅读:
    三个Bootstrap免费字体和图标库
    前端实时消息提示的效果-websocket长轮询
    带分页的标签
    VMware-workstation安装
    摄影/肥猫的大头贴
    Smith Numbers(分解质因数)
    C
    B
    Ball
    Property Distribution(DFS)
  • 原文地址:https://www.cnblogs.com/xiaochongchong/p/9964987.html
Copyright © 2011-2022 走看看