Browse Source

refine glob usage

czhen 3 years ago
parent
commit
984ac94d99
2 changed files with 23 additions and 10 deletions
  1. 7 7
      express/src/app.ts
  2. 16 3
      express/src/utils/index.ts

+ 7 - 7
express/src/app.ts

@@ -14,7 +14,7 @@ import {
   LoggingInterceptor,
   ErrorInterceptor,
 } from "./interceptors";
-import { getDirectories, generateCfgs } from "./utils";
+import { getDirectories, getDirectoriesSync, generateCfgs } from "./utils";
 import * as path from "path";
 
 const PLUGIN_DEV = process.env?.PLUGIN_DEV;
@@ -65,8 +65,8 @@ io.on("connection", (socket: Socket) => {
 
 // Read plugin files and start express server
 // Import all plguins under "src/plugins"
-getDirectories(SRC_PLUGIN_DIR, async (dirErr: Error, dirRes: [string]) => {
-  const cfgs: any = [];
+getDirectories(SRC_PLUGIN_DIR, async (dirErr: Error, dirRes: string[]) => {
+  const cfgs: any[] = [];
   if (dirErr) {
     console.log("Reading plugin directory Error", dirErr);
   } else {
@@ -74,18 +74,18 @@ getDirectories(SRC_PLUGIN_DIR, async (dirErr: Error, dirRes: [string]) => {
   }
   // If under plugin dev mode, import all plugins under "../../src/*/server"
   if (PLUGIN_DEV) {
-    await getDirectories(
+    getDirectoriesSync(
       DEV_PLUGIN_DIR,
-      (devDirErr: Error, devDirRes: [string]) => {
+      (devDirErr: Error, devDirRes: string[]) => {
         if (devDirErr) {
-          console.log("Reading plugin directory Error", dirErr);
+          console.log("Reading dev plugin directory Error", devDirErr);
         } else {
           generateCfgs(cfgs, devDirRes, false);
         }
       }
     );
   }
-  console.log(cfgs);
+  console.log("======/api/plugins configs======", cfgs);
   cfgs.forEach(async (cfg: any) => {
     const { api: pluginPath, componentPath } = cfg;
     if (!pluginPath) return;

+ 16 - 3
express/src/utils/index.ts

@@ -4,14 +4,27 @@ import fs from "fs";
 // Utils: read files under specified directories
 export const getDirectories = (
   src: string,
-  callback: (err: Error, res: [string]) => void
+  callback: (err: Error, res: string[]) => void
 ) => {
   glob(src + "/**/*", callback);
 };
 
+// sync: read files under specified directories
+export const getDirectoriesSync = (
+  src: string,
+  callback: (err: Error, res: string[]) => void
+) => {
+  try {
+    const results = glob.sync(src + "/**/*");
+    callback(undefined, results);
+  } catch (error) {
+    callback(error, []);
+  }
+};
+
 export const generateCfgs = (
-  cfgs: [any],
-  dirRes: [string],
+  cfgs: any[],
+  dirRes: string[],
   isSrcPlugin: boolean = true
 ) => {
   dirRes.forEach((item: string) => {