Last active
December 20, 2021 12:48
-
-
Save rlingineni/c24862e79b63225f09b67cfe740dc003 to your computer and use it in GitHub Desktop.
Converts flat html files into a directory structure with index.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Converts a flat file structure like: | |
* about.html, features.html, blog.html | |
* into | |
* features/index.html, about/index.html, blog/index.html | |
* Usage: node cleaner.js or node cleaner.js watch | |
*/ | |
const fs = require("fs") | |
const watchDir = "./src" | |
const destDir = "./docs" | |
const args = process.argv | |
if (args && args.includes("watch")) { | |
console.log("Watching for File Changes") | |
// if you want to watch a source dir | |
fs.watch( | |
watchDir, { | |
recursive: true, | |
}, | |
(event, filename) => { | |
if (filename) { | |
console.log(`${filename} file Changed`) | |
processFiles() | |
} | |
} | |
) | |
} else { | |
processFiles() | |
} | |
function processFiles() { | |
// read the output dir | |
const files = fs.readdirSync(destDir) | |
// if the file name is not index.html | |
// create a folder, move that file into it, and rename it to index.html | |
for (const file of files) { | |
if (file.includes(".html") && file !== "index.html") { | |
const fileName = file.split(".")[0] | |
if (!fs.existsSync(`${destDir}/${fileName}`)) { | |
fs.mkdirSync(`${destDir}/${fileName}`) | |
} | |
fs.copyFileSync(`${destDir}/${file}`, `${destDir}/${fileName}/index.html`) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment