我将如何从外部 URL 获取代码并在 NodeJS 中执行它

How would i get code from an external URL and execute it in NodeJS

本文关键字:NodeJS 执行 取代码 获取 从外部 URL      更新时间:2023-09-26

我需要创建一个 NodeJS 脚本,该脚本将从我的 VPS 上托管的脚本自动更新。为此,我需要从我的VPS获取代码并将其发送到客户端,客户端将像在客户端中一样执行代码。我不知道如何实现这一点...我有什么:

客户:

WebSocket = require('ws')
ws = new WebSocket('ws://localhost:8720');
var getinit_init_key = "jN*&gbhh*&G8ihae8rwgh78g&*G&*G&GFUibg&GB*&GVBWG";
var getINITKey = JSON.stringify({ init: getinit_init_key, userip: 'server',   reason: 'getUpdate' });
ws.on('open', function open() {
    ws.send(getINITKey);
});
ws.on('message', function(data, flags) {
    d = JSON.parse(data)
    d.x();
});

服务器:

update1 = require('./socks.js') //socks.js is my code
update2 = update1.init
update = JSON.stringify({ x: update2.toString() });
var ws = require("nodejs-websocket");
var server = ws.createServer(function(conn) {
    console.log("Got new connection!");
    conn.on("text", function(data) {
        try {
            conn.sendText(update)
            console.log(JSON.parse(update).x);
        }
        catch (error) {
            console.log("RECOVERED FROM ERROR: " +error)
        }
    });
    conn.on("close", function(code, reason) {
        console.log('Sent Update to User');
    });
    conn.on("error", function(error) {
        console.log("Recovered from Error");
    });
}).listen(8720);

实际上,您可以将代码作为js文件放在外部源代码上,并使用<script>标记在客户端代码中,您可以导入代码,例如如何从CDN使用jquery.js。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

导入后,您可以直接使用该 js 文件中的方法。