+
35
-

回答

当然可以,Node.js 更适合做这种“根据 URL 动态执行脚本”的服务,下面我给你写一个完整示例:

目标功能(Node.js):

访问 http://localhost:3000/test.js;

自动加载 ./test.js 文件;

执行它(支持 console.log、函数、导出);

将结果返回给前端。

 Node.js 服务器代码:server.js

const http = require('http');
const fs = require('fs');
const vm = require('vm');
const path = require('path');
const url = require('url');

const server = http.createServer((req, res) => {
    const parsedUrl = url.parse(req.url);
    const pathname = decodeURIComponent(parsedUrl.pathname);

    // 只允许访问 .js 文件
    if (pathname.endsWith('.js')) {
        const filepath = path.join(__dirname, pathname);

        if (fs.existsSync(filepath)) {
            try {
                const code = fs.readFileSync(filepath, 'utf-8');
                const sandbox = {
                    console: {
                        log: (...args) => sandbox.output.push(args.join(' '))
                    },
                    output: []
                };

                vm.createContext(sandbox); // 创建沙箱环境
                vm.runInContext(code, sandbox);

                const output = sandbox.output.join('\n');
                res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
                res.end(output || '[no output]');
            } catch (err) {
                res.writeHead(500, { 'Content-Type': 'text/plain' });
                res.end(`Execution error:\n${err.stack}`);
            }
        } else {
            res.writeHead(404, { 'Content-Type': 'text/plain' });
            res.end('Script not found.');
        }
    } else {
        res.writeHead(403, { 'Content-Type': 'text/plain' });
        res.end('Only .js files are allowed.');
    }
});

server.listen(3000, () => {
    console.log('Server running at http://localhost:3000/');
});

示例脚本:test.js

console.log("Hello from test.js");
console.log("2 + 3 =", 2 + 3);

✅ 使用方式:

node server.js

然后访问:

http://localhost:3000/test.js

你会看到浏览器返回内容:

Hello from test.js
2 + 3 = 5

 注意事项:

支持 console.log
支持函数逻辑
安全性❌ 沙箱简单,不适合公网使用
可支持 POST/参数

网友回复

我知道答案,我要回答