Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Folder Structure:

Folder

Node.js Version 16.10;
Windows 10 Pro 21H2

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading