Polyglot Programming with Metacall
Calling Python from Node without spawning a subprocess. Metacall loads foreign functions through a shared C ABI.

I wanted to call Python from Node without spawning a subprocess every time. Metacall loads scripts in other languages and exposes their functions through a shared C ABI, so you can invoke them from JavaScript like ordinary callbacks.
This post walks through a minimal example: a Python add function called from a Node app.
What is Metacall? Metacall is a language-agnostic library that allows developers to call functions across different programming languages. It works by providing a common interface for functions written in different languages. This means that a function written in Python can be called from a Node.js application, or a function written in Ruby can be called from a C++ application.
Metacall supports a wide range of programming languages, including Python, Node.js, Ruby, C++, and many more. It also has a plugin system that allows developers to add support for new languages.
Getting Started with Metacall Before we can start using Metacall, we need to install it. Metacall provides pre-built binaries for most popular operating systems, as well as Docker images. We'll use the pre-built binary for Ubuntu Linux in this example.
To install Metacall on Ubuntu Linux, we can use the following commands in the terminal:
wget https://raw.githubusercontent.com/metacall/install/master/install.sh
chmod +x install.sh
sudo ./install.sh
Once Metacall is installed, we can start using it. Let's create a simple example to demonstrate how it works.
First, we'll create a Python function that adds two numbers together:
# add.py
def add(a, b):
return a + b
Next, we'll create a Node.js application that calls the add function:
// app.js
const { metacall, metacall_load_from_file } = require('metacall');
// Load the Python script
metacall_load_from_file('py', ['./add.py']);
// Call the add function
metacall('add', 2, 3, (result) => {
console.log(result); // Output: 5
});
In this example, we use the metacall_load_from_file function to load the add.py file. We then call the add function using the metacall function, passing in the arguments 2 and 3. The result is returned in a callback function.
Conclusion Polyglot programming can be challenging, but it can also be very powerful. Metacall makes it easier to create polyglot applications by providing a common interface for functions written in different languages.
In this blog post, we've explored how Metacall can be used to create polyglot applications. We've also seen how to install and use Metacall to call a Python function from a Node.js application.
If you're interested in learning more about Metacall, check out the official documentation.