node.jstypescript

How to write a getFileExists function that starts at the source directory or project root in nodejs


How to update my getFileExists() function to start at the project root or the project source directory?

I made a function getFileExists() in nodejs but after a while I realized that it seems to be relative to the file that is calling it. OR NO?

So if I call it from /project/src/routes/file.ts then it checks in the src/routes folder:

export function getFileExists(path): boolean {
   var fileExists: boolean = false;

   try {
     fileExists = fs.existsSync(path);
   } catch (error) { }

   return fileExists;
}

I know there's a working directory command or variable in node js but how do I incorporate that in to the file system calls?

And is working directory the root of the project? or is that the src folder? Or is there a better variable for that?

UPDATE:
I just ran another test and it seems to be starting from the project root? So I don't know what it is.

Here is my other function that seems to be incorrect?

// get the correct path to the public folder
// this is not accurate because it is checking the folder of this file instead of the project root
export function getRootPath() {
  var rootPath = path.join(__dirname, "../public");
  if (__dirname.indexOf("/folder1/folder2/")==0) {
    rootPath = path.join(__dirname, "../../public");
  }
  return rootPath;
}

UPDATE 2
Upon further testing the first function mentioned seems to work and starts at the project root. It is the second function that is and was having issues. It may have issues because the path is added by nodejs express server with the line:

app.use(express.static('public'));

Update 3:
There seems to be a bit of info missing. I have a directory in the root of the project that is called uploads and the source in src. If I use __dirname I get the src directory. I have used app.use(express.static('uploads')); and that seemed to work until recently.

I need to get the path to the uploads directory.


Solution

  • There is a global const called __dirname, so you just need to combine the two paths, like this:

    const path = require('path');
    
    const filePath = path.join(__dirname, yourPath);
    

    and then you check it:

    fileExists = fs.existsSync(filePath)