Home > Blockchain >  Relative path not working but absolute works
Relative path not working but absolute works

Time:12-10

I'm trying to load an image to use it with canvas in node.js. Always getting a not found error. Here's the code:

const Canvas = require('canvas')

async function execute() {

    const canvas = Canvas.createCanvas(1080, 611);
    const context = canvas.getContext('2d');

    const license = await Canvas.loadImage('../../data/media/images/license.jpg');
    context.drawImage(license, 0, 0, canvas.width, canvas.height);
}

execute();

It somehow works with the path from the explorer (P:\\bot stuff\\darling.js\\src\\data\\media\\images\\license.jpg).

The thing that confuses me even more is that const { color } = require('../../data/config.json'); works perfectly fine, and that in the same file...

Folder Structure:

Folder

Node.js Version 16.10; Windows 10 Pro 21H2

CodePudding user response:

The behavior of require(...) is always resolved according to its own rules in the relative path of the file by the require.resolve(...) function.

However, Canvas.loadImage. Because it's loading part implemented in C, it can have different behavior than Node and has no context for the current js file location.

I recommend you to resolve the path based on __dirname explicitly.

  • Related