Loading modules on the fly?

Posted on
  • I was thinking in a way to loading modules on the fly and decide at runtime if I save then or not to the board.
    I want the code itself to download modules as needed (by some configuration, for example), when the board is runing standalone, not connected to the WebIDE or something.

    Is it possible? There is a good way to do that?

    I was reading in https://www.espruino.com/Modules that WiFi-enabled Espruino will soon be able to require() stuff online. Will this work on other boards as well (like ESPxxxx)? Is that what I'm looking for?

    Thank you.

  • At the moment there's nothing built in, and adding the module loading (despite it still being in the docs) is actually very low priority.

    The problem (much like on desktop) is that the require call is synchronous but the actual HTTP GET is async, so it would be a bit tricky to combine them. And while it might be possible to hack around it on normal Espruino boards, on ESP8266 I think it would likely fail completely (because it really dislikes functions that take a long time to execute).

    However nothing stops you from writing your own async loadModule function that you can call yourself (which will work on all platforms) - it just can't be automatic. All it has to do is request the JS file from http://www.espruino.com/modules/ and then call http://www.espruino.com/Reference#l_Modu­les_addCached with it as a string.

  • I'm just updating those docs for modules. The following works:

    function loadModule(moduleName, callback) {
      require("http").get("http://www.espruino­.com/modules/"+moduleName+".js", function(res) {
        var contents = "";
        res.on('data', function(data) { contents += data; });
        res.on('close', function() { 
          Modules.addCached(moduleName, contents); 
          if (callback) callback();
        });
      }).on('error', function(e) {
        console.log("ERROR", e);
      });
    }
    

    (but it's not synchronous)

  • Thank you so much!

    Now I will hack it around to accomplish my world domination plan using Espruino. :)

  • Worth noting that you probably want to download the .min.js module rather than the .js one as it'll save a bunch of space

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Loading modules on the fly?

Posted by Avatar for EthraZa @EthraZa

Actions