简体   繁体   中英

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. 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');

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:

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. Then I used http.request to load and eval specific parts from the remote server when needed. 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. 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. If you don't want your code public, npm also has new private module options.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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