需求:執行node腳本遍歷文件
解決:創建demo.js文件,如下

1 const path = require('path') 2 const fs = require('fs') 3 4 // ./dist 5 const basePath = './dist' 6 7 function mapDir(dir, callback, finish) { 8 fs.readdir(dir, function(err, files) { 9 if (err) { 10 console.error(err) 11 return 12 } 13 files.forEach((filename, index) => { 14 let pathname = path.join(dir, filename) 15 fs.stat(pathname, (err, stats) => { // 讀取文件信息 16 if (err) { 17 console.log('獲取文件stats失敗') 18 return 19 } 20 if (stats.isDirectory()) { 21 mapDir(pathname, callback, finish) 22 } else if (stats.isFile()) { 23 if (['.json', '.less'].includes(path.extname(pathname))) { // 過濾文件 24 return 25 } 26 // todo something 27 28 fs.readFile(pathname, (err, data) => { 29 if (err) { 30 console.error(err) 31 return 32 } 33 callback && callback(data) 34 }) 35 } 36 }) 37 if (index === files.length - 1) { 38 finish && finish() 39 } 40 }) 41 }) 42 } 43 44 //執行目錄遍歷 45 mapDir( 46 basePath, 47 function(file) { 48 // console.log('TCL: file', file.toString()) 49 // 讀取文件后的處理 50 }, 51 function() { 52 // console.log('xxx文件目錄遍歷結束') 53 } 54 )
運行 node demo.js進行文件遍歷