3

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 "../"

SigmaTheFox
  • 103
  • 1
  • 6
  • Request with what?, `require`, `readFile`, or something else.? – Keith Oct 24 '19 at 08:14
  • with require, but sometimes I use neither of them, depending on the package I'm using – SigmaTheFox Oct 24 '19 at 08:16
  • 1
    Can we see the code that's failing sometimes?.. – Keith Oct 24 '19 at 08:18
  • I edited the post with the example code – SigmaTheFox Oct 24 '19 at 08:23
  • That's not using `require` to load, it's using something called `Canvas.loadImage`, I'm not sure what that is, but for things like `readFile` that it's likely using try and avoid using relative paths here, as there relative to current working directory, and that can change during program execution. Instead use `path.join` with `__dirname`.. eg. `loadImage(path.join(__dirname, './images/halloween/background.jpg'))` – Keith Oct 24 '19 at 10:36

1 Answers1

1

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.

foobar2k19
  • 84
  • 4
  • so basically what you're saying is that even though I'm trying to request within the command file, `"./"` can sometimes be relative to the command file and other times to index.js? – SigmaTheFox Oct 24 '19 at 08:28
  • Node will resolve paths relative to the file for you if you're interacting with another javascript file, it will not for other types of files. – foobar2k19 Oct 24 '19 at 08:35