node.jscanvasnode-canvas

How to avoid multi-byte file path bug of node-canvas's loadImage?


node-canvas (2.7.0) has bug which cannot load image from the path includes multi-bytes characters.

const { loadImage } = require('canvas');

const image = await loadImage('/Users/ユーザ名/Documents/test.png');

Such case causes "File not found" error.

How to avoid this?


Solution

  • We should wait official bug fix, but following works as work-around:

    const { Image } = require('canvas');
    const fs = require('fs');
    
    const image = await new Promise((res, rej) => {
      fs.readFile('/Users/ユーザ名/Documents/test.png', (err, buf) => {
        if (err) rej(err);
        const img = new Image();
        img.onload = () => { res(img) };
        img.onerror = (err) => { rej(err) };
        img.src = buf;
      });
    });