使用场景:工作中经常制作H5广告,需要做预加载机制,而文件数据需要通过外部进行加载,使用node的fs模块,可以快速地生成json文件,下面是代码解读;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| var path = require("path"); var fs = require("fs");
var customUrl = { relative: "../../src/assets/airWar/images", stitching: "assets/airWar/images", output:path.join(__dirname,"../output") }
var url = path.join(__dirname, customUrl.relative); var results = { data:[] }
var fileLength = 0;
readDir(url); function readDir(_url) { fs.readdir(_url, function (err, files) { fileLength+=files.length; if (err) { console.log(err); return false; } files.forEach(function (filename) { let isHide = (/^\./).test(filename); if (!isHide) { let fsStats = fs.statSync(`${_url}/${filename}`); if (fsStats.isDirectory()) { fileLength-=1; customUrl.stitching += `/${filename}`; readDir(`${_url}/${filename}`); } else if (fsStats.isFile()) { console.log("this is file"); results.data.push(`${customUrl.stitching}/${filename}`); console.log(results.data.length,fileLength); if(results.data.length===fileLength){ writeFile(); } } }else{ fileLength-=1; } }); }); }
function writeFile(){ fs.writeFile(`${customUrl.output}/manifest.json`,JSON.stringify(results),function (err){ if(err){ return console.log(err); } console.log(`文件创建成功`); }); }
|