generated from tailored/router-template
50 lines
1.4 KiB
TypeScript
50 lines
1.4 KiB
TypeScript
import http from 'http';
|
||
import send from 'send';
|
||
import fs from 'fs';
|
||
import path from 'path';
|
||
import { ProxyInfo } from './proxy.ts';
|
||
import { checkFileExists } from '@/file/index.ts';
|
||
|
||
export const fileProxy = (req: http.IncomingMessage, res: http.ServerResponse, proxyApi: ProxyInfo) => {
|
||
// url开头的文件
|
||
const url = new URL(req.url, 'http://localhost');
|
||
const [user, key, _info] = url.pathname.split('/');
|
||
const pathname = url.pathname.slice(1);
|
||
const { indexPath = '', target = '', rootPath = process.cwd() } = proxyApi;
|
||
try {
|
||
// 检测文件是否存在,如果文件不存在,则返回404
|
||
let filePath = '';
|
||
let exist = false;
|
||
if (_info) {
|
||
filePath = path.join(rootPath, target, pathname);
|
||
exist = checkFileExists(filePath, true);
|
||
}
|
||
if (!exist) {
|
||
filePath = path.join(rootPath, target, indexPath);
|
||
exist = checkFileExists(filePath, true);
|
||
}
|
||
console.log('filePath', filePath, exist);
|
||
|
||
if (!exist) {
|
||
res.statusCode = 404;
|
||
res.end('Not Found File');
|
||
return;
|
||
}
|
||
const ext = path.extname(filePath);
|
||
let maxAge = 24 * 60 * 60 * 1000; // 24小时
|
||
if (ext === '.html') {
|
||
maxAge = 0;
|
||
}
|
||
let sendFilePath = path.relative(rootPath, filePath);
|
||
const file = send(req, sendFilePath, {
|
||
root: rootPath,
|
||
maxAge,
|
||
});
|
||
file.pipe(res);
|
||
} catch (error) {
|
||
res.statusCode = 404;
|
||
res.end('Error:Not Found File');
|
||
return;
|
||
}
|
||
};
|