Search code examples
javascriptpythonnode.jspyv8

Embedding Node.js in Python


I am looking at the option of embedding node.js into python to add node.js functionality to my existing python code. I know that it can be done the other way around, as described in this post. However, I want to keep the as much of the existing Python project intact as possible, which means allowing Python to manage execution.

PyV8 does just about everything I want except provide a node.js-like environment that would allow me to use node.js modules in PyV8, so it seems like a good starting point.

Does node.js provide an external API similar to that of V8 such that one could modify PyV8 to wrap node.js? If not, is there a way to load the node.js environment into PyV8 so I can use node.js modules?

Thanks!


Solution

  • What you want to do is not supported. Unlike, say, the CPython interpreter, or even the V8 JavaScript interpreter, Node.js was not designed to be embedded, has no interface for doing so, and no serious plan to change that.

    I can't find any official documentation on that, but there are numerous threads like this one that give the relevant information.

    But that doesn't mean it's impossible. The top layer of Node isn't that complicated, and really you'd just need to patch out a few parts of it to do different things. And, in fact, people have tried to do exactly that, in projects like tacnode. I don't know if any of them are ready for prime time or not, but it may be worth looking at them, especially if you're willing and able to contribute if they're incomplete.

    Of course that only gets you embedding in C or C++; you still need to embed in Python. But wrapping a C shared library so you can use it in Python (well, CPython and PyPy) is a long-solved problem; Python has had extension modules since almost the beginning, as well as ctypes and cffi if you don't want to write any C code. And there are third-party projects like Cython to let you write almost-Python code that directly calls your shared library as if it were native C, and compiles to a Python extension module.

    So, it's almost certainly doable, but it's probably not going to be trivial, or packaged and ready to go out of the box.