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

      

      

  • 相关阅读:
    [转][C#]文件流读取
    03-算数运算符
    02-bytes和str
    01-爬虫必备基础知识
    如何使用油猴脚本不要vip就能观看各大视频网站如腾讯,爱奇艺等的vip视频
    django下的framework
    centos6.7升级python3.6.1
    python 连接sqlserver: pymssql
    pycharm中提交Git 忽略部分代码
    jmeter 性能插件
  • 原文地址:https://www.cnblogs.com/xiaochongchong/p/9964987.html
Copyright © 2011-2022 走看看