WebAssembly কি?
WebAssembly (Wasm) হল একটি বাইনারি ইন্সট্রাকশন ফরম্যাট যা উচ্চ-স্তরের ভাষা যেমন C, C++ এবং Rust-এর জন্য পোর্টেবল অ্যাসেম্বলি টার্গেট হিসেবে ডিজাইন করা হয়েছে।
ওয়েব অ্যাসেম্বলির মূল বৈশিষ্ট্য:
বাইনারি বিন্যাস
আকারে ছোট, জাভাস্ক্রিপ্টের চেয়ে দ্রুত লোড এবং চালানো
নেটিভ পারফরম্যান্সের কাছাকাছি
নেটিভ মেশিন কোড গতির কাছাকাছি চলে
প্ল্যাটফর্ম স্বাধীন
ব্রাউজার, Node.js এবং অন্যান্য পরিবেশে চলে
নিরাপত্তা
একটি শক্তিশালী নিরাপত্তা মডেল সহ একটি স্যান্ডবক্সযুক্ত পরিবেশে চলে
জাভাস্ক্রিপ্টের বিপরীতে, WebAssembly একটি নিম্ন-স্তরের বাইনারি বিন্যাস নয় যা ম্যানুয়ালি লিখতে হবে।
পরিবর্তে, আপনি WebAssembly-এ অন্যান্য ভাষা থেকে কোড কম্পাইল করেন।
Node.js-এ WebAssembly সমর্থন
Node.js WebAssembly WebAssembly ( ).
আপনার Node.js সংস্করণ WebAssembly সমর্থন করে কিনা তা পরীক্ষা করতে:
উদাহরণ: WebAssembly সমর্থন চেক করুন
console.log(typeof WebAssembly === 'object');
console.log(WebAssembly);
দ্রষ্টব্য:
WebAssembly সমর্থন প্রথম Node.js v8.0.0 এ যোগ করা হয়েছিল এবং পরবর্তী সংস্করণে উন্নত করা হয়েছিল।
Node.js-এ WebAssembly ব্যবহার করা
Node.js WebAssembly API WebAssembly :
| পদ্ধতি | ব্যাখ্যা |
|---|---|
| WebAssembly.compile() | WebAssembly বাইনারি একটি গ্রীষ্মকালীন WebAssembly প্যাকেজে কম্পাইল করে |
| WebAssembly.instantiate() | WebAssembly গ্রীষ্ম কম্পাইল এবং অবিলম্বে কার্যকর করা হয় |
| WebAssembly.validate() | WebAssembly বাইনারি বিন্যাস যাচাই করে |
| WebAssembly.Module | একটি সংকলিত WebAssembly সমাবেশ প্রতিনিধিত্ব করে |
| WebAssembly.Instance | একটি তাত্ক্ষণিক WebAssembly প্যাকেজ প্রতিনিধিত্ব করে |
| WebAssembly.Memory | WebAssembly মেমরি প্রতিনিধিত্ব করে |
উদাহরণ: Node.js-এ WebAssembly চালানো
const fs = require('fs');
// Read the WebAssembly binary file
const wasmBuffer = fs.readFileSync('./simple.wasm');
// Compile and instantiate the module
WebAssembly.instantiate(wasmBuffer).then(result => {
const instance = result.instance;
// Call the exported 'add' function
const sum = instance.exports.add(2, 3);
console.log('2 + 3 =', sum); // Output: 2 + 3 = 5
});
দ্রষ্টব্য:
এই উদাহরণে simple.wasm ফাইলটি হবে একটি সংকলিত WebAssembly প্যাকেজ যা 'add' ফাংশন রপ্তানি করে। আপনি সাধারণত C, C++ বা রাস্ট কোড কম্পাইল করে এটি তৈরি করেন।
বিভিন্ন ভাষা নিয়ে কাজ করা
Node.js C, C++, Rust WebAssembly :
Emscripten সহ C/C++
Emscripten হল C/C++ এর জন্য একটি কম্পাইলার টুলচেন যা WebAssembly প্রকাশ করে।
উদাহরণ সি কোড (add.c):
#include
EMSCRIPTEN_KEEPALIVE
int add(int a, int b) {
return a + b;
}
WebAssembly হিসাবে কম্পাইল:
emcc add.c -s WASM=1 -s EXPORTED_FUNCTIONS='["_add"]' -o add.js
wasm-pack সঙ্গে মরিচা
wasm-pack হল মরিচা-উত্পাদিত WebAssembly-এর জন্য একটি টুলকিট।
উদাহরণ মরিচা কোড (src/lib.rs):
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
ওয়াসম-প্যাক দিয়ে কনফিগার করুন:
wasm-pack build --target nodejs
উন্নত WebAssembly অ্যাপ্লিকেশন
1. জটিল ডেটা স্ট্রাকচার নিয়ে কাজ করা
JavaScript এবং WebAssembly এর মধ্যে জটিল ডেটা পাস করার জন্য যত্নশীল মেমরি ব্যবস্থাপনা প্রয়োজন:
উদাহরণ: WebAssembly-এ অ্যারে পাঠানো
// JavaScript code
const wasmModule = await WebAssembly.instantiate(wasmBuffer, {
env: {
memory: new WebAssembly.Memory({ initial: 1 })
}
});
// Allocate memory for an array of 10 integers (4 bytes each)
const arraySize = 10;
const ptr = wasmModule.exports.alloc(arraySize * 4);
const intArray = new Int32Array(wasmModule.exports.memory.buffer, ptr, arraySize);
// Fill array with values
for (let i = 0; i < arraySize; i++) {
intArray[i] = i * 2;
}
// Call WebAssembly function to process the array
const sum = wasmModule.exports.processArray(ptr, arraySize);
console.log('Sum of array:', sum);
// Don't forget to free the memory
wasmModule.exports.dealloc(ptr, arraySize * 4);
সংশ্লিষ্ট সি কোড (WebAssembly হিসাবে সংকলিত):
#include
int* alloc(int size) {
return (int*)malloc(size);
}
void dealloc(int* ptr, int size) {
free(ptr);
}
int processArray(int* array, int length) {
int sum = 0;
for (int i = 0; i < length; i++) {
sum += array[i];
}
return sum;
}
2. WebAssembly সহ মাল্টিথ্রেডিং
WebAssembly Web Workers এবং SharedArrayBuffer এর মাধ্যমে মাল্টিথ্রেডিং সমর্থন করে:
উদাহরণ: WebAssembly-এর সাথে সমান্তরাল প্রক্রিয়াকরণ
// main.js
const workerCode = `
const wasmModule = await WebAssembly.instantiate(wasmBuffer, {
env: { memory: new WebAssembly.Memory({ initial: 1, shared: true }) }
});
self.onmessage = (e) => {
const { data, start, end } = e.data;
const result = wasmModule.exports.processChunk(data, start, end);
self.postMessage({ result });
};
`;
// Create worker pool
const workerCount = navigator.hardwareConcurrency || 4;
const workers = Array(workerCount).fill().map(() => {
const blob = new Blob([workerCode], { type: 'application/javascript' });
return new Worker(URL.createObjectURL(blob));
});
// Process data in parallel
async function processInParallel(data, chunkSize) {
const results = [];
let completed = 0;
return new Promise((resolve) => {
workers.forEach((worker, i) => {
const start = i * chunkSize;
const end = Math.min(start + chunkSize, data.length);
worker.onmessage = (e) => {
results[i] = e.data.result;
completed++;
if (completed === workerCount) {
resolve(results);
}
};
worker.postMessage({ data, start, end });
});
});
}
3. WebAssembly ডিবাগিং
WebAssembly ডিবাগ করা চ্যালেঞ্জিং হতে পারে, কিন্তু আধুনিক টুল সাহায্য করতে পারে:
Emscripten এর সাথে সোর্স ম্যাপ ব্যবহার করা
# Compile with debugging information and source maps
emcc -g4 --source-map-base http://localhost:8080/ -s WASM=1 -s EXPORTED_FUNCTIONS='["_main","_my_function"]' -o output.html source.c
Chrome DevTools-এ ডিবাগিং
রিয়েল-ওয়ার্ল্ড ওয়েব অ্যাসেম্বলি উদাহরণ
1. WebAssembly এর মাধ্যমে ইমেজ প্রসেসিং
WebAssembly CPU- নিবিড় কাজগুলিতে ভাল কাজ করে, যেমন ইমেজ প্রসেসিং:
// JavaScript wrapper for WebAssembly image processing
async function applyFilter(imageData, filterType) {
const { instance } = await WebAssembly.instantiate(wasmBuffer, {
env: { memory: new WebAssembly.Memory({ initial: 1 }) }
});
const { width, height, data } = imageData;
// Allocate memory for image data
const imageDataSize = width * height * 4; // RGBA
const imageDataPtr = instance.exports.alloc(imageDataSize);
// Copy image data to WebAssembly memory
const wasmMemory = new Uint8Array(instance.exports.memory.buffer);
wasmMemory.set(new Uint8Array(data.buffer), imageDataPtr);
// Apply filter
instance.exports.applyFilter(imageDataPtr, width, height, filterType);
// Copy result back to ImageData
const resultData = new Uint8ClampedArray(
wasmMemory.slice(imageDataPtr, imageDataPtr + imageDataSize)
);
// Free allocated memory
instance.exports.dealloc(imageDataPtr, imageDataSize);
return new ImageData(resultData, width, height);
}
2. ক্রিপ্টোগ্রাফি
WebAssembly সহ উচ্চ-পারফরম্যান্স ক্রিপ্টোগ্রাফিক অপারেশন:
// Example: Using the Web Crypto API with WebAssembly
async function encryptData(data, keyMaterial) {
// Import WebAssembly crypto module
const { instance } = await WebAssembly.instantiateStreaming(
fetch('crypto.wasm'),
{ env: { memory: new WebAssembly.Memory({ initial: 1 }) } }
);
// Generate IV (Initialization Vector)
const iv = window.crypto.getRandomValues(new Uint8Array(12));
// Prepare data
const dataBytes = new TextEncoder().encode(JSON.stringify(data));
const dataPtr = instance.exports.alloc(dataBytes.length);
new Uint8Array(instance.exports.memory.buffer, dataPtr, dataBytes.length)
.set(dataBytes);
// Encrypt data using WebAssembly
const encryptedDataPtr = instance.exports.encrypt(dataPtr, dataBytes.length);
// Get encrypted data from WebAssembly memory
const encryptedData = new Uint8Array(
instance.exports.memory.buffer,
encryptedDataPtr,
dataBytes.length // In real usage, you'd track the actual encrypted size
);
// Clean up
instance.exports.dealloc(dataPtr, dataBytes.length);
return {
iv: Array.from(iv),
encryptedData: Array.from(encryptedData)
};
}
সম্পদ এবং পরবর্তী পদক্ষেপ
Node.js WebAssembly :
কর্মক্ষমতা
গণনামূলকভাবে নিবিড় কাজের জন্য নেটিভ অপারেটিং গতির কাছাকাছি
ভাষা নির্বাচন
আপনার Node.js অ্যাপ্লিকেশনে C, C++, Rust, Go এবং অন্যান্য ভাষা ব্যবহার করুন
কোড পুনরায় ব্যবহার
অন্যান্য ভাষা থেকে বিদ্যমান লাইব্রেরি এবং কোডবেস পুনরায় ব্যবহার করুন
আইসোমরফিক কোড
ব্রাউজার এবং সার্ভারের মধ্যে WebAssembly মডিউল শেয়ার করুন
সাধারণ ব্যবহারের ক্ষেত্রে:
কর্মক্ষমতা তুলনা
পারফরম্যান্সের সুবিধাগুলি প্রদর্শন করতে, আসুন একটি পুনরাবৃত্ত ফিবোনাচি ফাংশনের জাভাস্ক্রিপ্ট এবং ওয়েব অ্যাসেম্বলি বাস্তবায়নের তুলনা করি:
জাভাস্ক্রিপ্ট বাস্তবায়ন:
// Recursive Fibonacci in JavaScript (inefficient for demonstration)
function fibonacciJS(n) {
if (n <= 1) return n;
return fibonacciJS(n - 1) + fibonacciJS(n - 2);
}
সি বাস্তবায়ন (WebAssembly হিসাবে সংকলিত):
#include
// WebAssembly-optimized Fibonacci function
EMSCRIPTEN_KEEPALIVE
int fibonacci_wasm(int n) {
if (n <= 1) return n;
int a = 0, b = 1, temp;
for (int i = 2; i <= n; i++) {
temp = a + b;
a = b;
b = temp;
}
return b;
}
কর্মক্ষমতা তুলনা সূচক:
const fs = require('fs');
const path = require('path');
// Read the WebAssembly binary file
const wasmBuffer = fs.readFileSync('./fibonacci.wasm');
// JavaScript implementation for comparison
function fibonacciJS(n) {
if (n <= 1) return n;
return fibonacciJS(n - 1) + fibonacciJS(n - 2);
}
// Compile and instantiate the WebAssembly module
WebAssembly.instantiate(wasmBuffer).then(result => {
const { fibonacci_wasm } = result.instance.exports;
// Test with a value that's computationally expensive
const n = 40;
// Measure WebAssembly performance
const wasmStart = performance.now();
const wasmResult = fibonacci_wasm(n);
const wasmEnd = performance.now();
// Measure JavaScript performance
const jsStart = performance.now();
const jsResult = fibonacciJS(n);
const jsEnd = performance.now();
console.log(`Fibonacci(${n})`);
console.log(`WebAssembly: ${wasmResult} (${(wasmEnd - wasmStart).toFixed(2)} ms)`);
console.log(`JavaScript: ${jsResult} (${(jsEnd - jsStart).toFixed(2)} ms)`);
});
দ্রষ্টব্য:
WebAssembly সংস্করণ একটি পুনরাবৃত্তিমূলক অ্যালগরিদম ব্যবহার করে যা পুনরাবৃত্তিমূলক পদ্ধতির চেয়ে অনেক দ্রুত। এমনকি একই অ্যালগরিদম সহ, WebAssembly সাধারণত CPU- নিবিড় ক্রিয়াকলাপের জন্য তার বান্ডিল প্রকৃতির কারণে ভাল পারফর্ম করে।
বাস্তব বিশ্বের অ্যাপ্লিকেশন
Node.js WebAssembly :
| লাইব্রেরি | উদ্দেশ্য | ভাষা |
|---|---|---|
| Sharp | উচ্চ কর্মক্ষমতা ইমেজ প্রক্রিয়াকরণ | C++ |
| ffmpeg.wasm | ভিডিও এবং অডিও প্রসেসিং | C |
| sql.js | জাভাস্ক্রিপ্টের জন্য SQLite | C |
| zxing-wasm | বারকোড স্ক্যানিং | C++ |
| TensorFlow.js | মেশিন লার্নিং | C++ |
মেমরি ব্যবস্থাপনা
WebAssembly মডিউলগুলি একটি রৈখিক মেমরিতে চলে, যা WebAssembly এবং JavaScript উভয় থেকে অ্যাক্সেসযোগ্য বাইটগুলির একটি সংলগ্ন, পরিবর্তনযোগ্য অ্যারে।
WebAssembly মেমরি বোঝা
WebAssembly মেমরি পৃষ্ঠাগুলিতে সংগঠিত, প্রতিটি পৃষ্ঠা 64KB (65,536 বাইট)।
মেমরি জাভাস্ক্রিপ্ট বা WebAssembly প্যাকেজ দ্বারা তৈরি করা যেতে পারে।
initial
প্রাথমিক পৃষ্ঠার সংখ্যা (ন্যূনতম আকার)
maximum
ঐচ্ছিক সর্বাধিক সংখ্যক পৃষ্ঠা মেমরি বাড়তে পারে
shared
কর্মীদের মধ্যে মেমরি ভাগ করা যেতে পারে (মাল্টিথ্রেডিংয়ের জন্য)
WebAssembly মেমরি তৈরি এবং অ্যাক্সেস করা
// Create a new WebAssembly Memory instance with 1 page (64KB) initially,
// and a maximum of 10 pages (640KB)
const memory = new WebAssembly.Memory({
initial: 1,
maximum: 10
});
// Access the memory as a typed array in JavaScript
let bytes = new Uint8Array(memory.buffer);
// Write data to memory
for (let i = 0; i < 10; i++) {
bytes[i] = i * 10; // Write values 0, 10, 20, ..., 90
}
// Read data from memory
console.log('Memory contents:', bytes.slice(0, 10));
// Grow the memory by 1 page (returns the previous size in pages)
const previousPages = memory.grow(1);
console.log(`Memory grown from ${previousPages} to ${memory.buffer.byteLength / 65536} pages`);
// IMPORTANT: After growing memory, we need to create a new view
// because the ArrayBuffer is detached when memory grows
bytes = new Uint8Array(memory.buffer);
console.log('Memory size now:', bytes.length, 'bytes');
সতর্কতা:
WebAssembly মেমরি বাড়ার সাথে সাথে অন্তর্নিহিত ArrayBuffer ডিকমিশন করা হয় এবং একটি নতুন তৈরি করা হয়। এর মানে হল মেমরির যেকোন জাভাস্ক্রিপ্ট TypedArray ভিউ মেমরি বড় হওয়ার পরে পুনরায় তৈরি করা আবশ্যক।
বিভিন্ন TypedArray ভিউ ব্যবহার করে
একই মেমরির বিভিন্ন দৃষ্টিভঙ্গি বিভিন্ন উপায়ে ডেটা ব্যাখ্যা করার জন্য তৈরি করা যেতে পারে:
বিভিন্ন ধরনের ডেটা নিয়ে কাজ করা
const memory = new WebAssembly.Memory({ initial: 1 });
// Different views of the same memory
const bytes = new Uint8Array(memory.buffer); // Unsigned 8-bit integers
const ints = new Int32Array(memory.buffer); // Signed 32-bit integers
const floats = new Float32Array(memory.buffer); // 32-bit floating point
// Write an integer at the beginning of memory
ints[0] = 42;
// The same memory location viewed as bytes
console.log('42 as bytes:', Array.from(bytes.slice(0, 4)));
// Write a float
floats[1] = 3.14159;
// View the float as bytes and as an integer
const floatByteOffset = 1 * Float32Array.BYTES_PER_ELEMENT;
const floatIntValue = ints[floatByteOffset / Int32Array.BYTES_PER_ELEMENT];
console.log('3.14159 as bytes:', Array.from(bytes.slice(floatByteOffset, floatByteOffset + 4)));
console.log('3.14159 as int32:', floatIntValue);
চিত্র প্রক্রিয়াকরণের উদাহরণ
এখানে চিত্র প্রক্রিয়াকরণের জন্য WebAssembly মেমরি ব্যবহার করার একটি বাস্তব উদাহরণ রয়েছে:
গ্রেস্কেল রূপান্তরের জন্য WebAssembly C কোড
#include
#include
// WebAssembly optimized grayscale conversion
EMSCRIPTEN_KEEPALIVE
void grayscale_wasm(uint8_t* pixels, int length) {
// Process each pixel (RGBA format)
for (int i = 0; i < length; i += 4) {
// Calculate grayscale value using luminance formula
uint8_t gray = (uint8_t)(
(0.299 * pixels[i]) + // Red
(0.587 * pixels[i + 1]) + // Green
(0.114 * pixels[i + 2]) // Blue
);
// Set RGB channels to gray value
pixels[i] = gray; // Red
pixels[i + 1] = gray; // Green
pixels[i + 2] = gray; // Blue
// Alpha channel (pixels[i + 3]) remains unchanged
}
}
WebAssembly প্যাকেজ ব্যবহার করার জন্য Node.js কোড
const fs = require('fs');
const wasmBuffer = fs.readFileSync('./image_processing.wasm');
// Sample image data (RGBA format, 2x2 pixel image)
const imageData = new Uint8Array([
255, 0, 0, 255, // Red pixel
0, 255, 0, 255, // Green pixel
0, 0, 255, 255, // Blue pixel
255, 255, 0, 255 // Yellow pixel
]);
// Instantiate the WebAssembly module
WebAssembly.instantiate(wasmBuffer, {
env: {
memory: new WebAssembly.Memory({ initial: 1 })
}
}).then(result => {
const instance = result.instance;
const { grayscale_wasm } = instance.exports;
const memory = instance.exports.memory;
// Get a view of the WebAssembly memory
const wasmMemory = new Uint8Array(memory.buffer);
// Copy image data to WebAssembly memory
wasmMemory.set(imageData);
// Process the image (convert to grayscale)
grayscale_wasm(0, imageData.length);
// Get processed image data from WebAssembly memory
const processedData = wasmMemory.slice(0, imageData.length);
console.log('Original image:', imageData);
console.log('Grayscale image:', processedData);
});
জাভাস্ক্রিপ্টের সাথে ইন্টিগ্রেশন
WebAssembly এবং JavaScript Node.js এ একসাথে কাজ করতে পারে:
উদাহরণ: JavaScript এবং WebAssembly ইন্টিগ্রেশন
const fs = require('fs');
const wasmBuffer = fs.readFileSync('./math.wasm');
// JavaScript function that will use WebAssembly
async function calculateFactorial(n) {
// Instantiate the module
const result = await WebAssembly.instantiate(wasmBuffer);
const wasm = result.instance.exports;
// Use the WebAssembly factorial function
return wasm.factorial(n);
}
// Use our mixed JS/WebAssembly function
async function main() {
console.log('Calculating factorials:');
for (let i = 1; i <= 10; i++) {
const result = await calculateFactorial(i);
console.log(`${i}! = ${result}`);
}
}
main().catch(console.error);
সর্বোত্তম অনুশীলন:
একটি ভাল বিকাশকারী অভিজ্ঞতার জন্য JavaScript-এ অ্যাপ্লিকেশন লজিক রাখার সময় আপনার অ্যাপ্লিকেশনের পারফরম্যান্স-গুরুত্বপূর্ণ অংশগুলির জন্য WebAssembly ব্যবহার করুন৷
সারাংশ
WebAssembly নিম্নলিখিত অনুমতি দিয়ে Node.js ক্ষমতা প্রসারিত করে:
এটি Node.js কে উচ্চ কর্মক্ষমতা প্রয়োজন এমন অ্যাপ্লিকেশনগুলির জন্য একটি বহুমুখী প্ল্যাটফর্ম করে তোলে।