Home > Net >  Relative fs.readFileSync paths with Node.js
Relative fs.readFileSync paths with Node.js

Time:09-18

I'm trying to upload the photo from postman to the folder, but I got "no such file or directory". I guess it might be because I wrote :

fs.readFileSync("./uploads")

I have searched about ways to change the path, so I tried:

fs.readFileSync(path.resolve(__dirname, './uploads'))

Or:

fs.readFileSync(path.resolve(__dirname, 'uploads'))

Still doesn't work, does anyone know how to fix this? Thanks!!!!

CodePudding user response:

Use path.join instead:

fs.readFileSync(path.join(__dirname, 'uploads'))

CodePudding user response:

Things to consider:

  • __dirname returns the base path for the current script. For example, if your JavaScript is located at /my-project/src/foo.js, then __dirname == '/my-project/src'.
  • ./uploads does not seem to be a photo file (where is the conventional extension, like .png?). Are you trying to enumerate files in a directory? If yes, then you should use fs.readdirSync(...).

If possible, show your project structure so that we can see where uploads is located, and also show where is the entry point JavaScript.

  • Related