node 把檔案封裝一層資料夾
阿新 • • 發佈:2018-12-21
把 pages 下面的單個js檔案,封裝上一個資料夾
var glob = require("glob"); const fs = require("fs-extra"); const l = console.log; const dir = "./src/pages"; glob(`${dir}/*.js`, {}, function(er, files) { if (er) return console.error(er); let fses = files.map(handleFile); for (let el of fses) { createDir(el.dirName).then(r => { if (r) { moveFile(el.oldSrc, el.newSrc); } }); } }); async function createDir(directory) { try { await fs.ensureDir(directory); return !0; } catch (err) { console.error(err); return !1; } } async function moveFile(oldSrc, newSrc) { try { await fs.move(oldSrc, newSrc); console.log(`success! ${oldSrc} to ${newSrc}`); } catch (err) { console.error(err); } } function handleFile(p) { const dirName = p.replace(/(\.js)$/, ""); return { oldSrc: p, newSrc: `${dirName}/index.js`, dirName, }; }