node遍历给定目录下特定文件,内容合并到一个文件
生活随笔
收集整理的這篇文章主要介紹了
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
總結
以上是生活随笔為你收集整理的node遍历给定目录下特定文件,内容合并到一个文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Frame工作原理
- 下一篇: js计算工时,去周末,设置上下班时间