How to Install GPU.js Using npm in Node.js
This guide explains how to install GPU.js into a Node.js project using npm, fulfill the required environment prerequisites, and verify the installation with a quick code test to ensure GPU acceleration is working correctly.
Prerequisites
Before installing GPU.js, ensure you have Node.js and npm installed
on your machine. Because GPU.js relies on native bindings for WebGL
emulation in Node.js via gl (headless-gl), you must have
basic build tools installed on your operating system:
- Windows: Install Python and Visual Studio Build
Tools by running
npm install --global --production windows-build-toolsfrom an elevated PowerShell, or install them manually via the Visual Studio Installer. - macOS: Install Xcode Command Line Tools by running
xcode-select --install. - Linux (Ubuntu/Debian): Install the necessary
compilation libraries:
sudo apt-get install -y build-essential libxi-dev libglu1-mesa-dev libglew-dev
Step 1: Initialize Your Project
If you do not have an existing Node.js project, create a new
directory and initialize it with a package.json file:
mkdir gpu-demo
cd gpu-demo
npm init -yStep 2: Install GPU.js
Run the following command in your terminal to install the
gpu.js package:
npm install gpu.jsnpm will download the package and compile the required native modules for headless WebGL execution.
Step 3: Verify the Installation
To verify that the installation succeeded and GPU.js can execute
computations, create a test file named index.js and add the
following code:
const { GPU } = require('gpu.js');
const gpu = new GPU();
// Create a simple kernel function to multiply array values
const multiplyMatrix = gpu.createKernel(function(a, b) {
return a[this.thread.x] * b[this.thread.x];
}).setOutput([5]);
const result = multiplyMatrix([1, 2, 3, 4, 5], [2, 2, 2, 2, 2]);
console.log('Result:', result);Run the script using Node.js:
node index.jsIf the installation is successful, the output will display:
Result: Float32Array(5) [ 2, 4, 6, 8, 10 ]
If a hardware GPU is unavailable in your environment, GPU.js will automatically fall back to standard CPU execution without throwing an error.