1+ const { exec } = require ( 'child_process' ) ;
2+ const fs = require ( 'fs' ) ;
3+ const path = require ( 'path' ) ;
4+ const https = require ( 'https' ) ;
5+
6+ // 获取命令行参数中的端口号和baseUrl
7+ let port = process . argv [ 2 ] || 4000 ;
8+ const baseUrl = process . argv [ 3 ] || 'https://your-resource-domain.com' ;
9+
10+ // 验证端口号是否有效
11+ port = parseInt ( port ) ;
12+ if ( isNaN ( port ) || port < 1 || port > 65535 ) {
13+ console . error ( 'Invalid port number. Using default port 4000' ) ;
14+ port = 4000 ;
15+ }
16+
17+ // 原来的颜色代码是 0,115,128,我们改成更亮的蓝绿色
18+ const arrow = '\x1b[38;2;0;200;255m\u2192\x1b[0m' ; // 更亮的箭头颜色
19+ const label = '\x1b[37m' ; // 更亮的白色文本
20+ const value = '\x1b[38;2;0;255;255m' ; // 更亮的青色值
21+
22+ console . log ( `${ arrow } ${ label } Local: ${ value } http://127.0.0.1:${ port } \x1b[0m` ) ;
23+ console . log ( `${ arrow } ${ label } Base URL: ${ value } ${ baseUrl } \x1b[0m` ) ;
24+ const server = exec ( `http-server -p ${ port } ` ) ;
25+
26+ // 创建目录的函数
27+ function ensureDirectoryExists ( filePath ) {
28+ const dirname = path . dirname ( filePath ) ;
29+ if ( fs . existsSync ( dirname ) ) {
30+ return true ;
31+ }
32+ ensureDirectoryExists ( dirname ) ;
33+ fs . mkdirSync ( dirname ) ;
34+ }
35+
36+ // 下载文件的函数
37+ function downloadFile ( url , filePath ) {
38+
39+ ensureDirectoryExists ( filePath ) ;
40+
41+ // 如果文件已存在,跳过下载
42+ if ( fs . existsSync ( filePath ) ) {
43+ console . log ( `File already exists: ${ filePath } ` ) ;
44+ return ;
45+ }
46+
47+ const file = fs . createWriteStream ( filePath ) ;
48+ https . get ( url , response => {
49+ response . pipe ( file ) ;
50+ file . on ( 'finish' , ( ) => {
51+ file . close ( ) ;
52+ console . log ( `Downloaded: ${ filePath } ` ) ;
53+ } ) ;
54+ } ) . on ( 'error' , err => {
55+ fs . unlink ( filePath , ( ) => { } ) ; // 删除未完成的文件
56+ console . error ( `Download failed for ${ filePath } :` , err . message ) ;
57+ } ) ;
58+ }
59+
60+ // 获取标准输出
61+ server . stdout . on ( 'data' , ( data ) => {
62+ const output = data . toString ( ) ;
63+
64+ // 使用正则表达式匹配包含 404 错误的行并提取路径
65+ const match = output . match ( / G E T \s + ( [ ^ \s ] + ) \s + E r r o r \s + \( 4 0 4 \) / ) ;
66+
67+ if ( match ) {
68+ const missingFile = match [ 1 ] . replace ( / " / g, '' ) ; // 移除引号
69+ console . log ( 'Missing file:' , missingFile ) ;
70+
71+ // 构建完整的本地文件路径(从项目根目录开始)
72+ const localPath = path . join ( process . cwd ( ) , missingFile ) ;
73+
74+ // 使用命令行传入的baseUrl构建下载URL
75+ const downloadUrl = `${ baseUrl } ${ missingFile } ` ;
76+
77+ // 下载文件
78+ downloadFile ( downloadUrl , localPath ) ;
79+ }
80+ } ) ;
81+
82+ // 获取标准错误输出
83+ server . stderr . on ( 'data' , ( data ) => {
84+ console . error ( 'stderr:' , data . toString ( ) ) ;
85+ } ) ;
86+
87+ // 监听进程结束
88+ server . on ( 'close' , ( code ) => {
89+ console . log ( `http-server process exited with code ${ code } ` ) ;
90+ } ) ;
0 commit comments