index.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. let opts = {
  7. production: true,
  8. routesDir: "routes"
  9. };
  10. Object.assign(opts, options)
  11. let app = express();
  12. console.time("Build time");
  13. await fs.rm(path.join(process.cwd(), ".build/"), {recursive: true, force: true});
  14. let root = path.join(process.cwd(), opts.routesDir);
  15. await addRoute(root, root, app, opts);
  16. console.timeEnd("Build time");
  17. return app;
  18. }
  19. const addRoute = async (dir, root, app, opts)=>{
  20. const files = await fs.readdir(dir, {withFileTypes: true});
  21. const indexFile = await findIndexFile(dir);
  22. if(!indexFile) return;
  23. let route = dir.replace(root, "");
  24. route = route === "" ? "/" : route;
  25. if(opts.production){
  26. const bundle = await parseComponent(indexFile);
  27. const bundleLocation = dir.replace(opts.routesDir, "build");
  28. const htmlPath = path.join(bundleLocation, "index.html");
  29. await fs.mkdir(bundleLocation, {recursive: true});
  30. await fs.writeFile(htmlPath, bundle);
  31. app.get(route, async (req, res)=>{res.sendFile(htmlPath)});
  32. }else{
  33. app.get(route, async (req, res)=>{res.send(await parseComponent(indexFile))});
  34. }
  35. fs.rm(path.join(dir, "tmp/"), {recursive: true, force: true});
  36. for(let i = 0; i < files.length; i++){
  37. const curDir = path.join(dir, files[i].name);
  38. if(files[i].isDirectory()) {
  39. await addRoute(curDir, root, app, opts);
  40. }
  41. }
  42. }
  43. const findIndexFile = async (dir)=>{
  44. const neovanPath = path.join(dir, "index.neovan");
  45. const htmlPath = path.join(dir, "index.html");
  46. const [neovan, html] = await Promise.allSettled([
  47. fs.access(path.join(dir, "index.neovan"), constants.F_OK),
  48. fs.access(path.join(dir, "index.html"), constants.F_OK)
  49. ]);
  50. if(neovan.status === "fulfilled") return neovanPath;
  51. if(html.status === "fulfilled") return htmlPath;
  52. return null;
  53. }