node遍历给定目录下特定文件,内容合并到一个文件

需求:

把一个文件夹底下的js或者ts文件里的内容合并到一个文件,我们用这个文件来申请软件著作权。
遍历目录用了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);

  

  

posted @ 2018-11-15 17:39  小虫1  阅读(608)  评论(0编辑  收藏  举报