...

/

Running Hello World with Emscripten in Node.js

Running Hello World with Emscripten in Node.js

Learn how to run an Emscripten-generated WebAssembly binary with a Node.js server.

We'll cover the following...

In this section, we’ll see how to convert C/C++ code into the WebAssembly binary via Emscripten and run it along with Node.js.

Let’s follow the tradition of Brian Kernighan, by writing “Hello, world” with a slight twist. Let’s do a “Hello, Web”:

  1. First, we create a hello_web.c file:

Press + to interact
touch hello_web.c
  1. Launch your favorite editor and add the following code:

Press + to interact
#include <stdio.h>
int main() {
printf("Hello, Web!\n");
return 0;
}

It’s a simple C program with a main function. The main function is the entry point during the runtime. When this code is compiled and executed using Clang (clang sum.c && ./a.out), “Hello, Web!” is printed. Now, instead of Clang (or any other compiler), let’s compile the code with emcc.

Press + to interact
emcc hello_web.c
  1. Once completed, the following files are generated:

  • a.out.js

  • a.out.wasm

The generated JavaScript file is huge. It has more than 2,000 lines and is 109 KB in size. We’ll learn how to optimize the file size later.

Let’s run the generated JavaScript file using Node that will print out ...