Now that Electron has hit Chrome's 60s we can have proper module support. But of course, the standard (for very good reasons) prevents loading modules from file:
and it makes sense for both Electron and NW.js to adhere to the statusquo.
So if you were really excited and this bums you, don't worry, you are in for awesome things.
The future Electron eco-system offers two options for native ES modules:
-
Custom Electron protocol via Chromium's module loading subsystem
-
Custom NodeJS loaders via Node's module loading subsystem recommended
Both methods can coexist. In fact, so far from tests, it seems that at least for hybrid applications, using both methods together will be the more suitable path.
This focuses on the first.
Revision: Draft 2
Well, though flattering, I am not sure this will be "Electron documentation" material, I'm just a user with like three weeks worth of test with Electron (since beta 2.0.0-beta.1) and maybe twice that time in past eras.
So in this particular instance, I was torn between conventional wisdom to always IO asynchronously and between how Node's own module system handles file reading. They basically use a special flavour of fs exposed to them through
process.binding('fs')
which provides synchronous internalModuleReadFile and internalModuleStat, which I often rely on in my module loading tests to limit the number of variables in terms of performance. This internal read method simply returns contents as a string or an empty string if the operation fails (ie file not found or no access). Since we need the contents in a buffer, I assumed the internal read was basically reading a buffer, converting to string, and then we would be creating yet another buffer from that string to pass it to Electron, then chromium would convert to string… etc.So essentially, readFileSync sounded like the closest possible option to internal read file, but without redundant buffering.
I would always async reading, unless it becomes counterproductive, and the folks that designed fs.readFile thought it not to be their weapon of choice in very few instances (or maybe even for that very specific instance) and I have not encountered evidence that would support the implications of asynchronous loading resources that are most likely being requested sequential for optimal performance.
So, the one thing I would explore would be to use readFile for things that if not delivered instantaneously would block rendering or delay either "first-paint" or "interactive", and then use readFileSync for anything huge and anything that does not impact the "feels-like-native" experience. And for really huge though, I would suppose either bypassing protocols altogether or using a stream protocol as appropriate.