1

I have a Node application that is supposed to run on both Linux and Windows environments. Using the code below, I am able to successfully get this to run on Linux, but not on Windows (which I use Powershell to run). The format seems to be correct, but the path seems to be different.

On Linux, the path pathA/pathB/pathC/file.txt can easily be found in my project, but on Windows, this keeps getting transformed into C:\Logs\pathA\pathB\pathC\file.txt which always throws an error because this isn't where my file is. I want it to be something like C:\myActualProject\pathA\pathB\pathC\file.txt.

I have been following a number of solutions on Stack Overflow, but while they have been getting me closer (such as finding the right JS code to translate Linux paths into Windows paths and vice versa), they haven't helped me solve the issue altogether.

The line of code that I'm targeting, looks like this:

const ca = fs.readFileSync(path.resolve('pathA/pathB/pathC/file.txt'))

but more specifically, I'm looking at this:

path.resolve('pathA/pathB/pathC/file.txt')

I'm not sure why this is saving in the C:\Logs directory, but then again, I don't work with Windows that often either.

Could someone please help me figure out how to read files that exist within the project directories and not Logs?

mklement0
  • 382,024
  • 64
  • 607
  • 775
Chloe Bennett
  • 901
  • 2
  • 10
  • 23
  • I believe I found a solution with: https://stackoverflow.com/questions/3133243/how-do-i-get-the-path-to-the-current-script-with-node-js – Chloe Bennett Sep 23 '19 at 19:09
  • While `__dirname` / `__filename`, as shown in the linked post, _may_ work, the problem is that they're _source-file-specific_, and a given file may or may not reside directly in the project root folder. The `require.main.filename` approach below avoids that problem. Also, allow me to give you the standard advice in the next comment; I also encourage you to revisit all your previous questions and accept answers there, as appropriate. – mklement0 Sep 23 '19 at 20:05

1 Answers1

0

path.resolve() resolves paths relative to the current directory, which is not necessarily the same as your application directory (project directory).

Therefore, you must determine your application directory with path.resolve(require.main.filename + '/..') and append the relative path to it:

path.join(
  path.resolve(require.main.filename + '/..'), 
  'pathA/pathB/pathC/file.txt'
)
mklement0
  • 382,024
  • 64
  • 607
  • 775