Join GitHub today
GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.Sign up
[Discussion] Requiring Native Modules in the Renderer Process to be NAPI or Context Aware #18397
Native modules in Electron
Loading native modules in Electron has always been tricky. It's a pain to rebuild, to link to the right
We've always thought "wouldn't it be cool if we could change this". Now, with Node 12's Worker Threads, we see a way to do that.
Node ran into the same issue when they added worker threads: native modules could not be loaded in multiple workers. Node solved this by introducing the concept of "Context Aware" native modules. This is how native modules tell Node that they are safe to be loaded in multiple
Context Aware modules and NAPI modules can be instantated multiple times in Node even without our patched process model. As they become more common, our patches will bring less benefit and be more redundant.
What does this mean for Electron?
Right now, nothing. However, at some point in the future -- probably in a few major versions -- we intend to remove our process model patches. At that point, any native Node modules loaded in the renderer process must be either NAPI or Context Aware.
This won't happen tomorrow. It probably won't happen this year. But it will happen, so if you're using or maintaining a native module, you should start looking at the work to mark it as Context Aware. For lots of modules it's as easy as replacing
You may be wondering why we're changing something that (mostly) works? The main reasons are:
What does this look like for Native Module X?
The amount of work to become "Context Aware" will be different for every module. For native modules that act as proxies for native getters and setters -- i.e. they just expose JS apis to acccess native APIs -- it's normally as easy as adding a
Some modules will need to do cleanup when the context is destroyed to ensure the module doesn't leaking memory or to cause crashes. You can add hooks to clean up after yourself with
Are native modules the only reason for the "new process for every navigation"? The following explanation from @zcbenz seems to suggest that node can't fully tear down its one js environment per process, so a new one can take its place.
@bughit That situation has changed in recent times, as mentioned in the original issue text with the introduction of worker threads node now supports multiple instances of node per-process along with proper teardown support (this is what making your addon context aware supports). We already teardown node environments when the