Skip to content

Commit

Permalink
Fix a bug: CLI only accepts --config. --input command will throw errors
Browse files Browse the repository at this point in the history
Remove redundant functions/variables. Move the readfile into one functions

Change sync loop to async loop. Move the htmlConverter and indexGenerator function to a new file

add comments
  • Loading branch information
JiaHua-Zou committed Oct 15, 2021
1 parent 4aeba79 commit 207e0d5
Show file tree
Hide file tree
Showing 2 changed files with 214 additions and 200 deletions.
282 changes: 82 additions & 200 deletions fs-Handler.js
Original file line number Diff line number Diff line change
@@ -1,234 +1,116 @@
var fs = require("fs");
var fse = require("fs-extra");
const fs = require("fs");
const fse = require("fs-extra");
const path = require("path");
const { config } = require("yargs");
const { htmlConverter, indexGenerator } = require("./fs-html");

function isMarkDown(filename) {
return filename.substr(filename.length - 3) === ".md";
}


function readConfig(configPath) {
try {
// Read from the path specified
const configData = JSON.parse(fs.readFileSync(configPath, 'utf8'));
// Create data to export
let exp = {
"input": "",
"lang": ""
};

// Move over data from config file to export
if(configData.input)
exp.input = configData.input;
if(configData.lang)
exp.lang = configData.lang;

return exp;
} catch (err) {
console.log("Error in reading a config file");
console.log(err);
}
}

function readFile(fileSrc, configPath, lang = "en") {
//Main function
function Main(fileSrc, configPath, lang = "en") {
// Read configuration file if specified
let configs = {};
if(config)
if (configPath) {
configs = readConfig(configPath);
console.log(configs);
}

// Replace data from configs to variables
if(configs.input)
fileSrc = configs.input;
if(configs.lang)
lang = configs.lang;
if (configs.input) fileSrc = configs.input;
if (configs.lang) lang = configs.lang;

// Read the argument to find if it is a folder or a .txt file.
var fileDir;
fse
.emptyDir(process.cwd() + "/dist")
.then(() => {
console.log("Success!");
})
.catch((err) => {
console.log(err);
});
emptyDist();

if (fs.lstatSync(fileSrc).isDirectory()) {
fs.readdir(fileSrc, (err, files) => {
if (err) {
console.log(err);
process.exit(1);
console.log(`Error: ${err}`);
process.exit(-1);
}

fs.mkdir(process.cwd() + "/dist", { recursive: true }, (error) => {
if (error) {
console.log(`An error occurred: ${error}`);
} else {
files.forEach((file) => {
fs.stat(fileSrc + "/" + file, (err, stats) => {
if (err) {
console.log("An Errored has occurred!");
process.exit(1);
}
if (!stats.isDirectory()) {
fs.readFile(
fileSrc + "/" + file,
"utf8",
function (err, data) {
if (err) {
console.log(err);
process.exit(1);
}
fileDir = path.basename(file, ".txt") + ".html";
htmlConverter(data, fileDir, isMarkDown(file), lang);
}
);
}
});
process.exit(-1);
}
for (const file of files) {
fs.stat(fileSrc + "/" + file, (err, stats) => {
if (err) {
console.log("An Errored has occurred!");
process.exit(-1);
}
if (!stats.isDirectory()) {
readFile(file, fileSrc + "/" + file, lang);
}
});
indexGenerator(fileSrc, lang);
}
indexGenerator(fileSrc, lang);
});
});
} else {
var filename = fileSrc;
fs.readFile(filename, "utf8", function (err, data) {
if (err) {
console.log(err);
process.exit(1);
fs.mkdir(process.cwd() + "/dist", { recursive: true }, (error) => {
if (error) {
console.log(`An error occurred: ${error}`);
process.exit(-1);
}
fs.mkdir(process.cwd() + "/dist", { recursive: true }, (error) => {
if (error) {
console.log(`An error occurred: ${error}`);
} else {
fileDir = isMarkDown(filename)
? path.basename(filename, ".md") + ".html"
: path.basename(filename, ".txt") + ".html";
htmlConverter(data, fileDir, isMarkDown(filename), lang);
}
});
readFile(fileSrc, fileSrc, lang);
});
}
}

function htmlConverter(src, fileDirName, isMarkDown = false, lang) {
var fileName = "";
var text = "";
let htmlElement = "";
//Create the HTML file.
function readFile(fileSrc, fileDir, lang) {
console.log(`Creating file: ${fileSrc}`);
fs.readFile(fileDir, "utf8", function (err, data) {
if (err) {
console.log(err);
process.exit(-1);
}
fileSrc = isMarkDown(fileSrc)
? path.basename(fileSrc, ".md") + ".html"
: path.basename(fileSrc, ".txt") + ".html";
htmlConverter(data, fileSrc, isMarkDown(fileSrc), lang);
});
}

//.txt: will grab the title if there are 2 blank lines
var title = src.match(/^.+(\r?\n\r?\n\r?\n)/) || "";
//check if the file is a MarkDown or not.
function isMarkDown(filename) {
return filename.substr(filename.length - 3) === ".md";
}

//HTML <title> content will be taken from the file name or the var title.
if (!title) {
fileName = fileDirName.slice(0, -5);
text = src;
} else {
fileName = title[0].trim();
title = title[0].trim();
text = src.substring(fileName.length + 3);
//Empty out the dist folder.
function emptyDist() {
try {
fse
.emptyDir(process.cwd() + "/dist")
.then(() => {
console.log("Old file has been deleted!");
})
.catch((err) => {
console.log(err);
});
} catch (error) {
console.error(`Error: ${error}`);
}
}

if (!isMarkDown) {
htmlElement = text
.split(/\r?\n\r?\n/)
.map((para) => `<p>${para.replace(/\r?\n/, " ")}</p>`)
.join(" ");
} else {
//.md process for headers, code and line break
const htmlArr = [];
// console.log(text.split(/\r?\n/));
let isOpen = false;
text.split(/\r?\n/).forEach((e) => {
const arrData = e.split(" ");
arrData[0] =
arrData[0].startsWith("```") && arrData[0].length > 3
? "````"
: arrData[0];

// filter out the 3 and 1 backticks
if ((arrData[0] !== "```" && arrData[0] !== "`") && isOpen) {
arrData[0] = "e";
}
//will read the JSON config file.
function readConfig(configPath) {
try {
// Read from the path specified
console.log(configPath);
const configData = JSON.parse(fs.readFileSync(configPath, "utf8"));
// Create data to export
let exp = {
input: "",
lang: "",
};
// Move over data from config file to export
if (configData.input) exp.input = configData.input;
if (configData.lang) exp.lang = configData.lang;

//switch case for different markdown options
switch (arrData[0]) {
case "#":
htmlArr.push(`<h1>${arrData.slice(1).join(" ")}</h1><hr />\n`);
break;
case "##":
htmlArr.push(`<h2>${arrData.slice(1).join(" ")}</h2>\n`);
break;
case "###":
htmlArr.push(`<h3>${arrData.slice(1).join(" ")}</h3>\n`);
break;
case "`":
if(isOpen){
htmlArr.push(`</code>\n`);
isOpen = false;
}else{
htmlArr.push(`<code>\n`);
isOpen = true;
}
break;
case "```":
htmlArr.push(`</xmp>\n`);
isOpen = false;
break;
case "````":
htmlArr.push(`<xmp>\n`);
isOpen = true;
break;
case "":
htmlArr.push(`<br />\n`);
break;
case "e":
htmlArr.push(`${e}\n`);
break;
default:
htmlArr.push(`<p>${e}</p>\n`);
}
htmlElement = htmlArr.join("");
});
return exp;
} catch (err) {
console.log(`Error in reading a config file: ${err}`);
process.exit(-1);
}

//HTML template
var htmlBase =
`<!doctype html><html lang="${
lang == "" ? "en" : lang
}"><head><meta charset="utf-8">` +
`<title> ${fileName}</title>` +
`<meta name="viewport" content="width=device-width, initial-scale=1">` +
`</head><body><h1>${title}</h1>${htmlElement}</body></html>`;

fs.writeFile(`./dist/${fileDirName}`, htmlBase, function (err) {
if (err) console.log(err);
});
}

function indexGenerator(fileSrc, lang) {
fs.readdir(fileSrc, (err, files) => {
var list = "";
files.forEach((element) => {
console.log(element);
if (element != null) {
list += `<h3><a href="${
path.basename(element, ".txt") + ".html"
}">${path.basename(element, ".txt")}</a></h3>`;
}
});
var htmlBase =
`<!doctype html><html lang="${
lang == "" ? "en" : lang
}"><head><meta charset="utf-8">` +
`<title>Generated Site</title>` +
`<meta name="viewport" content="width=device-width, initial-scale=1">` +
`</head><body><h1>Generated Site</h1><div>${list}</div></body></html>`;

fs.writeFile(`./dist/index.html`, htmlBase, function (err) {
if (err) console.log(err);
console.log("Done!");
});
});
}
module.exports = readFile;
module.exports = Main;
Loading

0 comments on commit 207e0d5

Please sign in to comment.