Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ


Choose your language

InfoQ Homepage News JavaScript on a Toaster: Embedded JavaScript with Duktape

JavaScript on a Toaster: Embedded JavaScript with Duktape

Leia em Português

Software may be eating the world, but JavaScript may eat the software world. Duktape takes JavaScript beyond the confines of the browser or server with a full ECMAScript 5 compliant engine that can be embedded into any C/C++ project.

[Duktape's] small code base and simple build system make it the embedders dream. It's essentially just like the Lua project technically, but runs JavaScript which has a much bigger ecosystem and set of developers. — Tim Caswell

While Lua is not much older than JavaScript, the latter has garnered significant mind share with its ubiquity in the browser and on the server with node.js. For projects that want to embed a scripting langauge, Duktape provides access to a very popular language and its ecosystem. "The original motivation was to have a Lua-like implementation for JavaScript," says Sami Vaarala, the creator of Duktape.

Working with Duktape is as simple as adding duktape.c and duktape.h to a project. The bindings between JavaScript and C are bidirectional, so either can call the other. The 'Hello World!' example is:

#include "duktape.h"

int main(int argc, char *argv[]) {
  duk_context *ctx = duk_create_heap_default();
  duk_eval_string(ctx, "print('Hello world!');");
  return 0;

Tim Caswell has taken the core of Duktape and extended it with Dukluv to create a minimal "node.js-like environment for tiny devices." Caswell says that his project adds libuv bindings to Duktape, giving it

access to the operating system making it a fully general programming environment with non-blocking I/O, timers, sub-process support and loads of useful utility functions as provided in libuv.

The need to embed a scripting language is not new. Video games have done it for years, such as World of Warcraft which uses Lua for interface customization. According to a popular answer on Stack Overflow, Lua is often used because

it's small, portable, hackable ANSI C code base; easy to embed, extend, and -- most importantly for game developers -- it has a minimal runtime footprint

Browser engines like SpiderMonkey and V8 could be embedded, but their size makes them unusable for small applications. They are "far too heavyweight for simple tasks or lower-powered machines," Caswell says. The Espruino project also provides JavaScript for microcontrollers, but its ECMAScript compliance is only around 95% whereas Duktape is fully compliant.

Duktape comes with a MIT License and the source code is available on GitHub. Developers who have used it have praised its extensive documentation

Rate this Article