zyf-server
Version:
A modern HTTP static file server with Vue SSR directory listing, built for developers
80 lines • 2.37 kB
JavaScript
;
/**
* 文件服务类
* 处理所有文件系统相关操作
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileService = void 0;
const fs_1 = require("fs");
const path_1 = require("path");
const mime_1 = __importDefault(require("mime"));
class FileService {
/**
* 检查文件或目录是否存在
*/
async exists(path) {
try {
await fs_1.promises.access(path);
return true;
}
catch {
return false;
}
}
/**
* 获取文件统计信息
*/
async stat(path) {
return fs_1.promises.stat(path);
}
/**
* 读取目录内容
*/
async readDirectory(dirPath) {
const entries = await fs_1.promises.readdir(dirPath);
const items = [];
for (const entry of entries) {
const fullPath = (0, path_1.join)(dirPath, entry);
const stats = await this.stat(fullPath);
items.push({
name: entry,
path: entry,
isDirectory: stats.isDirectory(),
size: stats.isFile() ? stats.size : undefined,
mtime: stats.mtime,
});
}
// 排序:目录在前,然后按名称排序
return items.sort((a, b) => {
if (a.isDirectory && !b.isDirectory)
return -1;
if (!a.isDirectory && b.isDirectory)
return 1;
return a.name.localeCompare(b.name);
});
}
/**
* 发送文件内容
*/
async sendFile(filePath, _req, res, range) {
return new Promise((resolve, reject) => {
const stream = range
? (0, fs_1.createReadStream)(filePath, { start: range.start, end: range.end })
: (0, fs_1.createReadStream)(filePath);
stream.on('error', reject);
stream.on('end', resolve);
stream.pipe(res);
});
}
/**
* 获取文件MIME类型
*/
getMimeType(filePath) {
return mime_1.default.getType(filePath) || 'application/octet-stream';
}
}
exports.FileService = FileService;
//# sourceMappingURL=FileService.js.map