0Pricing
WebAssembly (WASM) for High Performance Apps · レッスン

Node.jsによるサーバーサイドWASM

WebAssemblyモジュールをNode.jsアプリケーションに統合し、高性能なサーバーサイドロジックやマイクロサービスを実現します

「Node.jsによるサーバーサイドWASM」はCoddyKit上の無料WebAssembly (WASM) for High Performance Appsレッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはWebAssembly (WASM) for High Performance Apps学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 WebAssembly (WASM) for High Performance Appsコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

Server WASM with Node.js

Welcome! In this lesson, we'll explore how WebAssembly (WASM) isn't just for browsers. We'll learn to integrate high-performance WASM modules directly into Node.js applications.

This allows you to leverage WASM's speed for server-side logic, microservices, and computationally intensive tasks.

Benefits of WASM on Server

Why bring WASM to the server?

  • Performance: Execute near-native code for demanding tasks.
  • Portability: Run the same WASM module across different server environments.
  • Security: WASM's sandboxed environment offers enhanced security for untrusted code.
  • Language Agnostic: Write high-performance logic in C, C++, Rust, Go, and more, then run it in Node.js.

Node.js's WASM Support

Node.js has built-in support for WebAssembly, making it straightforward to load and execute WASM modules. It provides the same WebAssembly global object available in browsers.

This means you can use familiar JavaScript APIs to interact with your compiled WASM code.

Our First C Module

Let's start with a very simple C function. We'll compile this C code into a WebAssembly module.

This function will just add two integers, demonstrating basic interaction.

int add_numbers(int a, int b) {
  return a + b;
}

Compiling C to WASM

To turn our C code into a WASM module, we use a toolchain like Emscripten. The command would look something like this:

emcc my_module.c -o my_module.wasm -s EXPORTED_FUNCTIONS="['_add_numbers']"

This creates my_module.wasm, which contains our compiled add_numbers function, ready for Node.js!

Loading WASM File

First, we need to read the .wasm file from our file system. Node.js's fs module is perfect for this.

Assume my_module.wasm is in the same directory.

const fs = require('fs');
const path = require('path');

async function loadWasm() {
  // In a real scenario, 'my_module.wasm' would be a compiled file.
  // For this runnable example, we use a dummy path.
  const wasmPath = path.resolve(__dirname, 'dummy.wasm'); 
  
  try {
    const bytes = await fs.promises.readFile(wasmPath); 
    console.log('WASM bytes loaded! (if file existed)');
  } catch (error) {
    console.log('Dummy WASM file not found, proceeding...');
  }
}

loadWasm();

Instantiating the Module

Once we have the WASM bytes, we use WebAssembly.instantiate() to compile and instantiate the module. This gives us an instance object with access to exported functions.

For a runnable example, we'll use a very small, self-contained WASM binary that adds two numbers.

const fs = require('fs');

async function loadAndInstantiateWasm() {
  // A minimal WASM binary for 'add(a, b) => a + b'
  const wasmCode = new Uint8Array([
    0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, // WASM magic and version
    0x01, 0x07, 0x01, 0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7f, // Type section: func(i32, i32) -> i32
    0x03, 0x02, 0x01, 0x00, // Function section: one function, type 0
    0x07, 0x07, 0x01, 0x03, 0x61, 0x64, 0x64, 0x00, 0x00, // Export section: export 'add' as func 0
    0x0a, 0x09, 0x01, 0x07, 0x00, 0x20, 0x00, 0x20, 0x01, 0x6a, 0x0b // Code section: get_local 0, get_local 1, i32.add
  ]);

  const { instance } = await WebAssembly.instantiate(wasmCode);
  console.log('WASM module instantiated!');
  // The 'instance' now holds our exported functions.
}

loadAndInstantiateWasm();

Calling Exported Functions

Now that our WASM module is instantiated, we can access its exported functions through instance.exports. Our WASM module exports an add function.

Let's call it and see the result!

const fs = require('fs');

async function callWasmFunction() {
  // A minimal WASM binary for 'add(a, b) => a + b'
  const wasmCode = new Uint8Array([
    0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, // WASM magic and version
    0x01, 0x07, 0x01, 0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7f, // Type section: func(i32, i32) -> i32
    0x03, 0x02, 0x01, 0x00, // Function section: one function, type 0
    0x07, 0x07, 0x01, 0x03, 0x61, 0x64, 0x64, 0x00, 0x00, // Export section: export 'add' as func 0
    0x0a, 0x09, 0x01, 0x07, 0x00, 0x20, 0x00, 0x20, 0x01, 0x6a, 0x0b // Code section: get_local 0, get_local 1, i32.add
  ]);

  const { instance } = await WebAssembly.instantiate(wasmCode);
  const result = instance.exports.add(10, 20); // Calling the 'add' function
  console.log('Result from WASM:', result);
}

callWasmFunction();

Passing Primitive Data

As shown, passing primitive data types like integers (i32) between Node.js (JavaScript) and WASM is straightforward. WASM modules often use i32 for integers and f32/f64 for floats.

JavaScript numbers are 64-bit floats, but they are implicitly converted when passed to WASM functions expecting integer types.

WASM in Node.js Check

You've learned how to load and interact with a WASM module in Node.js. Let's test your understanding.

Server-Side WASM Recap

Great job! You've learned how to integrate WebAssembly modules into Node.js applications.

  • WASM brings high performance and portability to server-side logic.
  • Node.js provides native APIs (WebAssembly.instantiate) for loading and running WASM.
  • You can compile code from languages like C/C++ to WASM using tools like Emscripten.
  • Interacting with WASM functions and passing primitive data is direct and efficient.

This opens up exciting possibilities for building performant and flexible server applications!

よくある質問

「Node.jsによるサーバーサイドWASM」レッスンは無料ですか?

はい。「Node.jsによるサーバーサイドWASM」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、WebAssembly (WASM) for High Performance Appsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 WebAssembly (WASM) for High Performance Appsコースには全4レッスンが含まれています。

「Node.jsによるサーバーサイドWASM」で何を学びますか?

WebAssemblyモジュールをNode.jsアプリケーションに統合し、高性能なサーバーサイドロジックやマイクロサービスを実現します ブラウザで直接実行するハンズオンコードでWebAssembly (WASM) for High Performance Appsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

WebAssembly (WASM) for High Performance Appsを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのWebAssembly (WASM) for High Performance Appsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/4です。

「Node.jsによるサーバーサイドWASM」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このWebAssembly (WASM) for High Performance Appsレッスンでコードを書いて実行できますか?

はい。すべてのWebAssembly (WASM) for High Performance Appsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. Node.jsによるサーバーサイドWASM
  2. Cloud FunctionsとサーバーレスWASM
  3. 組み込みシステムとエッジコンピューティング
  4. WASMで拡張可能なプラグインシステムを構築する
← WebAssembly (WASM) for High Performance Appsに戻る