简体   繁体   English

node.js:如何包含来自其他服务器的外部.js?

[英]node.js: How to include external .js from another server?

I am trying to include .js files that are located on another server into my node.js program. 我正在尝试将位于另一台服务器上的.js文件包含到我的node.js程序中。 Is this possible? 这可能吗?

I can´t use require('./local_file.js') and get something over the Internet like this: require('http://www.server.com/path/file.js'); 我不能使用require('./local_file.js')并通过Internet获得如下内容: require('http://www.server.com/path/file.js');

I´ve tried to make a http.request and then use eval(), but the scope is all wrong and the functions inside the external file remain undefined: 我尝试过创建一个http.request,然后使用eval(),但是范围是错误的,并且外部文件中的函数仍然未定义:

var source_string = load_contents_via_http('http://www.server.com/folder/file.js');
var source_string += '\n run_my_function();';
eval(source_string);

Does anyone have any suggestions? 有没有人有什么建议?

Edit (Solution): I solved my problem by repacking the essential parts into the script that runs on my local server, as mentioned by @zackehh. 编辑(解决方案):我将基本部分重新打包到运行在本地服务器上的脚本中,从而解决了我的问题,如@zackehh所述。 Then I used http.request to load and eval specific parts from the remote server when needed. 然后,当需要时,我使用http.request从远程服务器加载和评估特定部分。 Since the most important code was running on the server locally, the imported extra code was easier to add. 由于最重要的代码在本地服务器上运行,因此导入的额外代码更易于添加。

Here is a example on how I solved the problem: 这是有关我如何解决问题的示例:

var EssentialObject = {};
EssentialObject.ServerFunctions = {};
EssentialObject.ServerFunctions.Init = function (){
  var external_code = load_contents_via_http('http://www.server.com/file.js');
  var eval_this = external_code.substr(
    external_code.indexOf('EssentialObject.Addons = {}'),
    external_code.indexOf('// End of EssentialObject.Addons')-external_code.indexOf('EssentialObject.Addons = {}')
  );
  eval ( eval_this );
  eval ( "EssentialObject.Addons.test=true; console.log('Eval Done')" ); // Check if it works
};

Disclaimer: this technically isn't an answer to the question, I feel it should be classed as one, as it moves towards a solution to the problem. 免责声明:从技术上讲,这不是解决问题的方法,我认为应该将其归为一类,因为它正朝着解决问题的方向发展。

You could do it with a simple http request , but I don't recommend it. 可以通过一个简单的http请求 执行此操作,但我不建议这样做。 You would be better off repacking the things you need on both servers in npm modules and requiring them in. This allows you share your code pretty painlessly. 您最好将两台服务器上所需的内容重新打包到npm模块中,并要求它们放入其中。这使您可以毫不费力地共享代码。 If you don't want your code public, npm also has new private module options. 如果您不想公开代码,npm还提供了新的私有模块选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM