简体   繁体   中英

Relative path not working but absolute works

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:

文件夹

Node.js Version 16.10; Windows 10 Pro 21H2

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM