使用带有node.js的require加载远程js文件 [英] Loading remote js file using require with node.js

查看:968
本文介绍了使用带有node.js的require加载远程js文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用NodeJS和javascript工作在线套接字服务器,我一直在使用require在代码中创建playrooms:

I've been working on an online socket server using NodeJS and javascript, and I've been creating "playrooms" in my code using require:

new_game_obj = require('./forza4.js');

现在..当我在我的本地机器上测试我的代码时,这可以找到,但对于生产服务器我遇到了一个问题。看起来由于某些技术原因,运行我的代码的进程在我可以访问的机器上(用于文件上载等),因此我被服务器场上的人员要求更改我的代码,以便我将从全局位置加载forza4.js中的代码,而不是本地,就像我现在所做的那样。
所以我把代码更改为:

Now.. this works find when I test my code on my local machine, but for the production server I've been presented with a problem. It would seem that for some technical reason, the process that runs my code is on a different machine then the one I have access to (for file uploading, and such), so I was asked by the guys on the server farm to change my code so that I will load the code I have in "forza4.js" from a global position, and not local, like I do at the moment. So I changed the code to this:

new_game_obj = require('http://www.xxxxx.com/blabla/forza4.js');

(当然我测试了文件是否存在,只是为了确定,它显示在当我指向那个实际地址时的浏览器)
但是我的代码出错(再次,此时,我在我的机器上本地运行),其中说:

(Of course I tested to see if the file is there, just to be sure, it shows in the browser when I point to that actual address) But I get an error from my code (again, at this point, I'm running this locally on my machine), which says:


例外:错误:找不到模块' http://www.xxxxx.com/blabla/forza4.js '

所以只是为了安全方面,我做了:

So just to be on the safe side, I did:

new_game_obj = require('http://92.xx.xx.xx/blabla/forza4.js'); 

但同样的错误。

从远程服务器向我的代码加载扩展是否有问题,或者我只是将require调用格式化错误?

Should there be a problem loading an "extension" to my code from a remote server, or am I just formatting the "require" call wrong?

非常感谢!

Yuval。

PS
这是此主题的后续行动:
这是较旧且已解决的帖子

推荐答案

看一看在node.js 模块文档



具体来说,请参考需求算法

在node.js中, require 调用是同步的,因此无法加载不在文件系统上的文件(即来自外部URL) )。

Within node.js, require calls are synchronous, so it's not possible to load files that are not on your file system (ie, from an external url).

您可以通过 http请求 - 或者更好的是, https请求并使用内置的 vm 模块 - 甚至是 eval ,但这似乎不是一个好主意 - 如这个老问题

You could fetch the code through an http request - or, even better, an https request and run it with the built-in vm module - or even with eval, but that seems not a good idea - as suggested on this old question.

类似

https.get( 'https://www.xxxxx.com/blabla/forza4.js', function( res ){
  res.on( 'data', function( data ){
    vm.runInThisContext( data, 'remote/forza4.js' );
  });
});

注意:我没有测试此代码

当然,这不是最佳解决方案,但它是一种解决方案。

Sure it isn't the best solution, but is a solution.

这篇关于使用带有node.js的require加载远程js文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆