index.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. writeBundleFile(dir, await parseComponent(indexFile));
  26. }
  27. const findIndexFile = async (dir)=>{
  28. const neovanPath = path.join(dir, "index.neovan");
  29. const htmlPath = path.join(dir, "index.html");
  30. const [neovan, html] = await Promise.allSettled([
  31. fs.access(path.join(dir, "index.neovan"), constants.F_OK),
  32. fs.access(path.join(dir, "index.html"), constants.F_OK)
  33. ]);
  34. if(neovan.status === "fulfilled") return neovanPath;
  35. if(html.status === "fulfilled") return htmlPath;
  36. return null;
  37. }
  38. const writeBundleFile = async (dir, bundle)=>{
  39. const writeDir = dir.replace("routes", ".build");
  40. await fs.mkdir(writeDir, {recursive: true});
  41. await fs.writeFile(`${writeDir}/index.html`, bundle);
  42. }