要使用 Node.js 的 Express 框架动态执行某个目录下的 JavaScript 脚本,您可以参考以下步骤:
安装 Express 和必要的依赖项:npm init
npm install express
在您的项目目录下创建一个名为 app.js 的文件,并添加以下内容:const express = require('express');
const app = express();
const fs = require('fs');
const path = require('path');
const vm = require('vm');
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.get('/execute/:scriptName', (req, res) => {
const scriptName = req.params.scriptName;
const scriptPath = path.join(__dirname, 'scripts', `${scriptName}.js`);
fs.readFile(scriptPath, 'utf8', (err, scriptContent) => {
if (err) {
res.status(404).send('Script not found.');
return;
}
try {
const script = new vm.Script(scriptContent);
const scriptContext = vm.createContext({ console, req, res });
script.runInContext(scriptContext);
} catch (error) {
res.status(500).send('Error executing the script.');
}
});
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
这段代码创建了一个基本的 Express 服务器,通过访问 /execute/:scriptName 路径来动态执行名为 :scriptName 的 JavaScript 脚本。这些脚本应该位于项目目录下的 scripts 文件夹中。
在项目目录下创建一个名为 scripts 的文件夹,并在其中添加您希望执行的 JavaScript 脚本。例如,创建一个名为 hello.js 的脚本:
res.send('Hello, world!');
运行 Express 服务器:node app.js
浏览器中访问 http://localhost:3000/execute/hello 来执行 hello.js 脚本。您应该看到 "Hello, world!" 的输出。网友回复