Search code examples
javascriptnode.jsdirectorydiscord.jsdirectory-structure

Node.js is unable to find a file in another folder


I have a Discord bot I'm maintaining since a year, and a couple of months ago I changed a bit the file structure to clean it up and make it easier for me to know what's going on.

The thing is, whenever I try to request a file (with require) that is in a folder located in the bot's root directory, sometimes it works with "./" and other times it works with "../"

The current file structure is:

----commands  
-------commands.js(multiple files)  
----images  
-------halloween  
----------images.png/jpg(multiple images)  
----logs  
-------bot.log  
----modules  
------logger.js  
----settings  
-------config.json  
-emojis.json  
-gifs.json  
-index.js

Following the structure above, when for example I try to request one of the halloween images in a command, the logical thing to me would be to use "../images/halloween/image.png", but instead I have to use "./images/halloween/image.png" as if the "images" folder is within the "commands" folder

In one of the commands I have to use:

const logs = require("../modules/logger");  
const background = await Canvas.loadImage("./images/halloween/background.jpg");

I would like to know why this happens. It really messes with my brain seeing an error saying that a file was not found only because node.js decided that this time the parent directory is "./" instead of "../"


Solution

  • Assuming your commands file is making file system calls (because you're accessing an image from it), the directory you invoke your script from can matter. Make sure you're using the path utility to resolve your file locations. See NodeJS accessing file with relative path for more details.