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');
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:
Exception: Error: Cannot find module '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');
But again, the same error.
Should there be a problem loading an "extension" to my code from a remote server, or am I just formatting the "require" call wrong?
Thanks a bunch!
Yuval.
P.S. This is a follow up to this thread: This is the older and resolved post
In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.
Cases where it is necessary to use both “require” and “import” in a single file, are quite rare and it is generally not recommended and considered not a good practice. However, sometimes it is the easiest way for us to solve a problem. There are always trade-offs and the decision is up to you.
“Require” is built-in with NodeJS With require , you can include them in your JavaScript files and use their functions and variables. However, if you are using require to get local modules, first you need to export them using module.
Specifically, refer to the require algorithm
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).
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.
Something like
https.get( 'https://www.xxxxx.com/blabla/forza4.js', function( res ){
res.on( 'data', function( data ){
vm.runInThisContext( data, 'remote/forza4.js' );
});
});
Note: I did not test this code
Sure it isn't the best solution, but is a solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With