使用chartjs-node搭配canvas-prebuilt仍报‘Cairo not found’错误求助
Ah, I've run into this exact issue before! The root cause is that chartjs-node depends on canvas-prebuilt, which requires system-level graphics libraries like Cairo to compile and run. Your local Windows setup works because windows-build-tools includes all these dependencies out of the box, but Linux servers need you to install them manually. Here's how to fix it:
1. Install System-Level Dependencies
The required packages vary slightly depending on your Linux distribution:
For Ubuntu/Debian-Based Servers
Run this command to install all necessary libraries and build tools:
sudo apt-get update && sudo apt-get install -y libcairo2-dev libjpeg-dev libpango1.0-dev libgif-dev build-essential g++
This installs Cairo (the main missing library), JPEG/Pango for image/text rendering, and the build tools needed to compile the canvas module.
For CentOS/RHEL-Based Servers
Use yum (or dnf for newer versions) to install the equivalent packages:
# CentOS 7 and earlier sudo yum install -y cairo-devel libjpeg-turbo-devel pango-devel giflib-devel gcc-c++ # CentOS 8+ / RHEL 8+ sudo dnf install -y cairo-devel libjpeg-turbo-devel pango-devel giflib-devel gcc-c++
2. Clean and Reinstall Your npm Dependencies
Once the system libraries are in place, you'll need to clear any partially installed dependencies and rebuild:
# Remove existing node_modules and lock file to avoid conflicts rm -rf node_modules package-lock.json # Reinstall dependencies from scratch npm install
Bonus Tips
- Consider upgrading to the official
canvaspackage:canvas-prebuiltis no longer actively maintained. Switching to the officialcanvaspackage (npm install canvas) will give you better long-term support for Linux environments, and the API is nearly identical to what you're using now. - Match Node.js versions: Make sure your server's Node.js version is close to the one you used locally. Major version differences can sometimes cause unexpected compilation issues with native modules like canvas.
内容的提问来源于stack exchange,提问作者CaptainPlanet

