Loading remote js file using require with node.js

后端 未结 2 1830
日久生厌
日久生厌 2020-12-16 03:57

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 = req         


        
相关标签:
2条回答
  • 2020-12-16 04:44

    How about the 'require from URL' NPM package?

    Just found it - not tried it, yet! https://www.npmjs.com/package/require-from-url

    0 讨论(0)
  • 2020-12-16 04:54

    Take a look at the node.js modules docs

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

    Update

    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.

    0 讨论(0)
提交回复
热议问题