Writing native modules in C for QuickJS engine

Carlos Alberto
4 min readJul 20, 2019

--

Basic introduction to native C modules for QuickJS

Few days ago a new Javascript engine was released by Fabrice Bellard, the QEMU and FFmpeg creator.

This caught my eye, because I’m a Javascript developer and I’ve been always interested in NodeJS internals, so I saw a good opportunity to learn more about how the JS code is actually executed in a low level.

I know this engine was created with embedded systems in mind, is really tiny and lightweight, and taking advantage of fact that the code base is still small, I’m trying to understand how it works and mainly, how to extend it.

And that’s what I’m trying to explain here, not form an expert point of view, but a rookie and someone with basic knowledge about C++.

QuickJS is not a kind of NodeJS, it’s more like V8

I’ve seen a lot of confusion about if QuickJS is just a NodeJS replacement, it is not, actually, you can’t port code directly from NodeJS to QuickJS because NodeJS has it’s own APIs (fs, path, process, net, etc) and QuickJS has a very small set of native functions to play with.

So, to improve our understanding about it, we’re going create a very basic C module to run its functions from Javascript.

Getting started

Goal

What we want at the end of this article is to make this code work in an independent executable after compiling with QuickJS compiler:

Prepare the source

You can read the compiling instructions from https://bellard.org/quickjs/quickjs.html#Installation
After compiling all the source code with make, try to compile and run the code I described above with:

# compile
./qjsc -m -o my_module my_module.js
# run
./my_module

--

--