0Pricing
WebAssembly (WASM) for High Performance Apps · 강의

Node.js를 활용한 서버 측 WASM

고성능 서버 측 로직과 마이크로서비스를 위해 WebAssembly 모듈을 Node.js 애플리케이션에 통합합니다.

Node.js를 활용한 서버 측 WASM은(는) CoddyKit의 무료 WebAssembly (WASM) for High Performance Apps 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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/7 AI 튜터), CoddyKit PRO로 업그레이드하면 WebAssembly (WASM) for High Performance Apps 강의 전체를 잠금 해제할 수 있습니다. WebAssembly (WASM) for High Performance Apps 강의에는 총 4개의 강의가 포함되어 있습니다.

“Node.js를 활용한 서버 측 WASM”에서 뭘 배우나요?

고성능 서버 측 로직과 마이크로서비스를 위해 WebAssembly 모듈을 Node.js 애플리케이션에 통합합니다. 브라우저에서 직접 실행하는 실습 코드로 WebAssembly (WASM) for High Performance Apps을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

WebAssembly (WASM) for High Performance Apps을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 WebAssembly (WASM) for High Performance Apps은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“Node.js를 활용한 서버 측 WASM” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 WebAssembly (WASM) for High Performance Apps 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 WebAssembly (WASM) for High Performance Apps 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Node.js를 활용한 서버 측 WASM
  2. 클라우드 함수 및 서버리스 WASM
  3. 임베디드 시스템 및 엣지 컴퓨팅
  4. 확장 가능한 WASM 플러그인 시스템 구축
← WebAssembly (WASM) for High Performance Apps(으)로 돌아가기