Ver Fonte

chore(pkg-packaging): modify pkg packaging strategy to externalize static assets

ddx há 4 semanas atrás
pai
commit
2dd35b49ca
5 ficheiros alterados com 72 adições e 41 exclusões
  1. 25 3
      .build/h5_for_webserver.build.js
  2. 9 0
      .build/pkg/pkg.json
  3. 6 0
      .build/pkg/runtime-config.json
  4. 32 29
      .build/pkg/server.js
  5. 0 9
      pkg.json

+ 25 - 3
.build/h5_for_webserver.build.js

@@ -2,13 +2,14 @@
 
 const { execSync } = require('child_process');
 const path = require('path');
+const fs = require('fs-extra');
 
 const TARO_API_URL = ''; //
-const TARO_MQTT_URL ='ws://localhost:8083/mqtt';
+const TARO_MQTT_URL = 'ws://localhost:8083/mqtt';
 const rootDir = path.join(__dirname, '..');          // 项目根目录
 
 
-execSync(`taro build --type h5`, { cwd: rootDir, stdio: 'inherit', env: { ...process.env, TARO_API_URL ,TARO_MQTT_URL} }, (error, stdout, stderr) => {
+execSync(`taro build --type h5`, { cwd: rootDir, stdio: 'inherit', env: { ...process.env, TARO_API_URL, TARO_MQTT_URL } }, (error, stdout, stderr) => {
     if (error) {
         console.error(`Error executing command: ${error.message}`);
         return;
@@ -20,7 +21,28 @@ execSync(`taro build --type h5`, { cwd: rootDir, stdio: 'inherit', env: { ...pro
     console.log(`Command stdout: ${stdout}`);
 });
 try {
-    execSync('npm run pkg', { stdio: 'inherit', cwd: rootDir });
+    // Step 1: Copy static H5 resources from dist/h5 to .build/pkg/static
+    const sourceDir = path.join(__dirname, '..', 'dist', 'h5');
+    const destDir = path.join(__dirname, 'pkg', 'static');
+
+    if (!fs.existsSync(destDir)) {
+        fs.mkdirSync(destDir, { recursive: true });
+    }
+    fs.copySync(sourceDir, destDir);
+    console.log(`Copied static H5 resources from ${sourceDir} to ${destDir}`);
+
+    // Step 2: Execute the pkg packaging command
+    const pkgJsonPath = path.join(__dirname, 'pkg', 'pkg.json');
+    const entryPoint = path.join(__dirname, 'pkg', 'server.js'); // Specify the entry point
+    const outputPath = path.join(__dirname, 'pkg'); // Specify the output path
+    const pkgCommand = `npx pkg  ${entryPoint} --config ${pkgJsonPath} --output ${outputPath}/dros_server`;
+
+    try {
+        execSync(pkgCommand, { stdio: 'inherit' });
+        console.log('Packaging completed successfully.');
+    } catch (error) {
+        console.error('Error during packaging:', error);
+    }
 } catch (err) {
     console.error('Failed to execute npm run pkg:', err.message);
     process.exit(1);

+ 9 - 0
.build/pkg/pkg.json

@@ -0,0 +1,9 @@
+{
+  "name": "my-server",
+  "version": "1.0.0",
+  "main": "server.js",
+  "pkg": {
+    "targets": ["node18-linux-x64", "node18-win-x64"], 
+    "outputPath": "./dist"
+  }
+}

+ 6 - 0
.build/pkg/runtime-config.json

@@ -0,0 +1,6 @@
+{
+  "local-host": "0.0.0.0",
+  "local-port": 30001,
+  "remote-host":"http://101.43.219.60:7700",
+  "staticPath": "./static"
+}

+ 32 - 29
server.js → .build/pkg/server.js

@@ -5,9 +5,12 @@ const fs = require('fs');
 const path = require('path');
 const url = require('url');
 
-const ROOT = path.join(__dirname, 'dist', 'h5');
-const PORT = process.env.PORT || 3000;
-const REMOTE = 'http://101.43.219.60:7700';
+// 读取配置
+const configPath = process.env.CONFIG_PATH || './runtime-config.json';
+const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
+//const ROOT = path.join(__dirname, 'dist', 'h5');
+const PORT = config["local-port"];
+const REMOTE = config["remote-host"];//'http://101.43.219.60:7700';
 
 const mime = { '.html': 'text/html', '.js': 'application/javascript', '.css': 'text/css', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg', '.gif': 'image/gif', '.svg': 'image/svg+xml', '.ico': 'image/x-icon' };
 
@@ -43,42 +46,42 @@ function proxyToRemote(req, res) {
 
 /* ------- 静态文件服务函数 ------- */
 function serveStatic(req, res) {
-    let file = decodeURIComponent(req.url.split('?')[0]);
-    file = file === '/' ? '/index.html' : file;
-    const filePath = path.join(ROOT, file);
-    if (!filePath.startsWith(ROOT)) return res.writeHead(403).end('Forbidden');
+    const parsed = url.parse(req.url, true);
+    let pathname = parsed.pathname;
+
+    // 默认索引
+    if (pathname === '/') pathname = '/index.html';
+
+    // 安全限制:禁止跳出 static
+    const safePath = path.normalize(decodeURIComponent(pathname));
+    const STATIC_DIR = path.resolve(config.staticPath || './static');
+    const filePath = path.join(STATIC_DIR, safePath);
+    if (!filePath.startsWith(STATIC_DIR)) {
+        res.statusCode = 403;
+        res.end('Forbidden');
+        return;
+    }
     fs.readFile(filePath, (err, data) => {
         if (err) {
-            if (file !== '/index.html') {
-                fs.readFile(path.join(ROOT, 'index.html'), (e, d) => {
-                    if (e) return res.writeHead(500).end('Server Error');
-                    res.writeHead(200, { 'Content-Type': 'text/html' }); res.end(d);
-                });
-            } else res.writeHead(404).end('Not Found');
+            if (err.code === 'ENOENT') {
+                res.statusCode = 404;
+                res.end('Not Found');
+            } else {
+                res.statusCode = 500;
+                res.end('Internal Server Error');
+            }
             return;
         }
-        const ext = path.extname(filePath);
-        res.writeHead(200, { 'Content-Type': mime[ext] || 'application/octet-stream' });
+
+        const ext = path.extname(filePath).toLowerCase();
+        res.setHeader('Content-Type', mime[ext] || 'application/octet-stream');
         res.end(data);
     });
 }
 
 /* ------- 主入口 ------- */
+
 http.createServer((req, res) => {
-    // 处理日志请求--纪录
-    if (req.method === 'POST' && req.url === '/log') {
-        let body = '';
-        req.on('data', chunk => body += chunk);
-        req.on('end', () => {
-            try {
-                const { level, msg } = JSON.parse(body);
-                writeLog(level, msg);
-            } catch { }
-            res.writeHead(204);
-            res.end();
-        });
-        return;
-    }
     // 1. 预检直接 200
     if (req.method === 'OPTIONS') { res.writeHead(200); res.end(); return; }
 

+ 0 - 9
pkg.json

@@ -1,9 +0,0 @@
-{
-  "pkg": {
-    "scripts": "server.js",          
-    "assets": ["dist/h5/**/*"],      
-    "targets": ["node18-linux-arm64", "node18-win-x64", "node18-linux-x64"],
-    "outputPath": "dist/pkg-out",         
-    "compress": "GZip"               
-  }
-}