javascriptnode.jsswiftcocoanpm

How to run Node JS code from npm inside of Swift


I am making a Cocoa App & want to call Node JS package downloaded from npm to run from Swift.

I don't know if it is possible but I couldn't find anything on the internet. Can I call an npm package from Swift?

Although it will require Node to be shipped or to be on the computer of the user running the app, I don't mind it. But can this be done?

Or do I have to write the same Node code in Swift?


Solution

  • That's a great question. I will try to give you an overview of how these different systems work and a theoretical, but rather painful solution. Swift runs on the mobile end and manages its resources on a more low level approach.

    Javascript on the other hand is a general purpose language that requires a Virtual Machine(VM) that "understands" javascript, to be embedded into the system you are targeting. Thankfully, iOS has already done that with javascriptcore interface. With it, you can load up a Javascript bundle and evaluate any function from it.

    In theory, what you are suggesting would work like this:

    1. Find a bundled version of the package you want to run

    2. Load it up on the javascript VM using the JavaScriptCore interface

    3. Evaluate the function of the package

    Check out this great guide

    The great caveat of this approach is the platform specific calls of the npm bundle (for example Node.js' fs package does not exist).

    If that is the case then you should use a remote service that runs the code for your as cenk suggested.