index.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import fs from "node:fs/promises";
  2. import path from "path";
  3. import {constants} from "node:fs";
  4. import parseComponent from "./parseComponent.js";
  5. export default async (express, options = {})=> {
  6. console.time("Build Completed In");
  7. await fs.rm(path.join(process.cwd(), ".build/"), {recursive: true, force: true});
  8. const app = express();
  9. const root = path.join(process.cwd(), "routes");
  10. readFiles(root, root, app);
  11. app.use(express.static(path.join(process.cwd(), ".build")));
  12. console.timeEnd("Build Completed In");
  13. return app;
  14. }
  15. const readFiles = async (dir, root, app)=>{
  16. const files = await fs.readdir(dir, {withFileTypes: true});
  17. for(let i = 0; i < files.length; i++){
  18. let curDir = path.join(dir, files[i].name);
  19. if(files[i].isDirectory()) {
  20. readFiles(curDir, root, app);
  21. }
  22. }
  23. let indexFile = await findIndexFile(dir);
  24. if(!indexFile) return;
  25. await writeBundleFile(dir, await parseComponent(indexFile));
  26. fs.rm(path.join(dir, "tmp/"), {recursive: true, force: true});
  27. }
  28. const findIndexFile = async (dir)=>{
  29. const neovanPath = path.join(dir, "index.neovan");
  30. const htmlPath = path.join(dir, "index.html");
  31. const [neovan, html] = await Promise.allSettled([
  32. fs.access(path.join(dir, "index.neovan"), constants.F_OK),
  33. fs.access(path.join(dir, "index.html"), constants.F_OK)
  34. ]);
  35. if(neovan.status === "fulfilled") return neovanPath;
  36. if(html.status === "fulfilled") return htmlPath;
  37. return null;
  38. }
  39. const writeBundleFile = async (dir, bundle)=>{
  40. const writeDir = dir.replace("routes", ".build");
  41. await fs.mkdir(writeDir, {recursive: true});
  42. await fs.writeFile(`${writeDir}/index.html`, bundle);
  43. }