【问题标题】:How would i get code from an external URL and execute it in NodeJS我如何从外部 URL 获取代码并在 NodeJS 中执行它
【发布时间】:2016-02-13 03:59:01
【问题描述】:

我需要创建一个 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);

【问题讨论】:

    标签: javascript node.js get


    【解决方案1】:

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

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

    导入之后就可以直接使用那个js文件中的方法了。

    【讨论】:

    • 我使用的是 NodeJS,而不是 HTML 网页。
    • 可以放在require里面
    • 我发现了一些有用的东西: var http = require('http'), vm = require('vm'), concat = require('concat-stream'); http.get({ host: 'localhost', port: 80, path: '/foo.js' }, function(res) { res.setEncoding('utf8'); res.pipe(concat({ encoding: 'string ' }, function(ret) { vm.runInThisContext(ret, '/foo.js'); })); });但这只会像普通的 JavaScrpt 一样执行代码,而不是 Node
    猜你喜欢
    • 2016-01-31
    • 2011-07-14
    • 2013-03-06
    • 1970-01-01
    • 2016-05-12
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 2018-11-18
    相关资源
    最近更新 更多