我基于你的代码做了一些调整,接下来请更新记忆: 1. index2.js import Fastify from 'fastify'; import * as drpy from './libs/drpy.js'; import path from 'path'; import {fileURLToPath} from 'url'; const fastify = Fastify({logger: true}); const __dirname = path.dirname(fileURLToPath(import.meta.url)); console.log('__dirname:', __dirname); // 动态加载模块并根据 query 执行不同逻辑 fastify.get('/api/:module', async (request, reply) => { const moduleName = request.params.module; const query = request.query; // 获取 query 参数 const modulePath = path.join(__dirname, 'js', `${moduleName}.js`); try { // 根据 query 参数决定执行逻辑 if ('play' in query) { // 处理播放逻辑 const result = await drpy.play(modulePath); return reply.send(result); } if ('ac' in query && 't' in query) { // 分类逻辑 const result = await drpy.cate(modulePath); return reply.send(result); } if ('ac' in query && 'ids' in query) { // 详情逻辑 const result = await drpy.detail(modulePath); return reply.send(result); } if ('wd' in query) { // 搜索逻辑 const result = await drpy.search(modulePath); return reply.send(result); } if ('refresh' in query) { // 强制刷新初始化逻辑 const refreshedObject = await drpy.init(modulePath, true); return reply.send(refreshedObject); } // 默认逻辑,返回 home + homeVod 接口 const result_home = await drpy.home(modulePath); const result_homeVod = await drpy.homeVod(modulePath); const result = { class: result_home, list: result_homeVod } reply.send(result); } catch (error) { console.log('Error processing request:', error); reply.status(500).send({error: `Failed to process request for module ${moduleName}: ${error.message}`}); } }); // 启动服务 const start = async () => { try { await fastify.listen(5757); console.log('Server listening at http://localhost:5757'); } catch (err) { fastify.log.error(err); process.exit(1); } }; start(); 2. libs/drpy.js import * as utils from '../utils/utils.js'; // 使用 import 引入工具类 import {readFile} from 'fs/promises'; import vm from 'vm'; // Node.js 的 vm 模块 const {req} = await import('../utils/req.js'); const {sleep, sleepSync} = await import('../utils/utils.js'); // 缓存已初始化的模块 const moduleCache = new Map(); /** * 初始化模块:加载并执行模块文件,存储初始化后的 rule 对象 * 如果存在 `预处理` 属性且为函数,会在缓存前执行 * @param {string} filePath - 模块文件路径 * @param refresh 强制清除缓存 * @returns {Promise} - 返回初始化后的模块对象 */ export async function init(filePath, refresh) { if (moduleCache.has(filePath) && !refresh) { console.log(`Module ${filePath} already initialized, returning cached instance.`); return moduleCache.get(filePath); } try { let t1 = utils.getNowTime(); // 读取 JS 文件的内容 const fileContent = await readFile(filePath, 'utf-8'); // 创建一个沙箱上下文,注入需要的全局变量和函数 const sandbox = { console, req, sleep, sleepSync, utils, rule: {}, // 用于存放导出的 rule 对象 }; // 创建一个上下文 const context = vm.createContext(sandbox); // 执行文件内容,将其放入沙箱中 const script = new vm.Script(fileContent); script.runInContext(context); // 访问沙箱中的 rule 对象 const moduleObject = utils.deepCopy(sandbox.rule); // 检查并执行 `预处理` 方法 if (typeof moduleObject.预处理 === 'function') { console.log('Executing preprocessing...'); await moduleObject.预处理(); } // 缓存初始化后的模块 moduleCache.set(filePath, moduleObject); let t2 = utils.getNowTime(); moduleObject.cost = t2 - t1; return moduleObject; } catch (error) { console.log('Error in drpy.init:', error); throw new Error('Failed to initialize module'); } } /** * 调用模块的指定方法 * @param {string} filePath - 模块文件路径 * @param {string} method - 要调用的属性方法名称 * @returns {Promise} - 方法调用的返回值 */ async function invokeMethod(filePath, method) { const moduleObject = await init(filePath); // 确保模块已初始化 if (moduleObject[method] && typeof moduleObject[method] === 'function') { return await moduleObject[method](); // 调用对应的方法 } else { throw new Error(`Method ${method} not found in module ${filePath}`); } } // 各种接口调用方法 export async function home(filePath) { return await invokeMethod(filePath, 'class_parse'); } export async function homeVod(filePath) { return await invokeMethod(filePath, '推荐'); } export async function cate(filePath) { return await invokeMethod(filePath, '一级'); } export async function detail(filePath) { return await invokeMethod(filePath, '二级'); } export async function search(filePath) { return await invokeMethod(filePath, '搜索'); } export async function play(filePath) { return await invokeMethod(filePath, 'lazy'); } 3.utils/req.js export async function req(param) { // 模拟异步请求 return new Promise((resolve) => { setTimeout(() => { resolve(`Response for ${param}`); }, 1000); }); } 4.utils/utils.js // utils.js: 存放工具类方法 import pkg from 'lodash'; const {cloneDeep} = pkg; export function getTitleLength(title) { return title.length; // 返回标题长度 } export function getNowTime() { return (new Date()).getTime() } export async function sleep(ms) { // 模拟异步请求 return new Promise((resolve) => { setTimeout(() => { resolve(); }, ms); }); } export function sleepSync(ms) { const end = Date.now() + ms; // 获取当前时间并计算结束时间 while (Date.now() < end) { // 阻塞式等待,直到时间到达 } } export const deepCopy = cloneDeep 5. js/_360.js // js/_360.js var rule = { title: '标题1', description: '这是描述', category: '视频', class_parse: async () => { console.log('执行了分类获取') return [ {type_id: '1', type_name: '电影'}, {type_id: '2', type_name: '电视剧'}, {type_id: '3', type_name: '综艺'}, {type_id: '4', type_name: '动漫'}, ] }, 预处理: async () => { console.log('执行了预处理') rule.title = '360影视' }, 推荐: async () => { sleepSync(2000); console.log('进入了推荐') // return '这是推荐:' + rule.title return [ {vod_name: '测试电影1', vod_pic: '1.png', vod_remarks: '测试描述1', vod_id: 'http://www.1.com'}, {vod_name: '测试电影2', vod_pic: '2.png', vod_remarks: '测试描述2', vod_id: 'http://www.2.com'}, ] }, 一级: async () => { // await sleep(200); sleepSync(200); let html = await req('123'); console.log('title:', rule.title); console.log('html:' + html); return html + '\n' + '这是一级:' + rule.title }, 二级: async () => { return '这是二级:' + rule.title }, 搜索: async () => { return '这是搜索:' + rule.title }, lazy: async () => { return '这是播放:' + rule.title }, };