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);

  

  

转载于:https://www.cnblogs.com/xiaochongchong/p/9964987.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值