1

I am trying to read a file with fs.readFileSync and I'm running into some issues locating that file with __dirname. This is my directory structure:

/Users
  /me
    /Documents
      /myapp
        /services
          /myapp (node app here)
            /server
              /templates
                /docx
                 -word2016_tpl.docx
              /methods
                /documents
                 -fetchDocument.ts

I am trying to read the file word2016_tpl.docx from fetchDocument.ts. When I read the file as a static string, everything works perfectly. Like so:

const buff = fs.readFileSync(
'/Users/me/Documents/myapp/services/myapp/server/templates/docx/word2016_tpl.docx'
);

However, clearly the above is not a good practice so I am trying to dynamically generate the file path using __dirname.

In fetchDocument.ts, I have:

console.log('current directory: ', __dirname);

// current directory:  /server/methods/documents

My question is, where is the preceeding /Users/me/Documents/myapp/services/myapp/ and how do I access it?

Edit:

I've also tried reading the file with fs.readFileSync('/server/templates/docx/word2016_tpl.docx') and that doesn't work

  • You can just type `DriveName:/Rest of the path`, can’t you? – MrMythical Sep 02 '21 at 16:26
  • by DriveName do you mean `/Users/me/Documents/myapp/services/myapp/`? if so, I don't want to statically write that because I don't think that would work in production – Jake Wright Sep 02 '21 at 16:34
  • Usually people have `C:` or `D:` or `E:` – MrMythical Sep 02 '21 at 16:35
  • am I misunderstanding how `__dirname` works? From reading other stackoverflow questions it seems like it's supposed to return the entire path. I'm on a mac so my path starts with `/Users/me` – Jake Wright Sep 02 '21 at 16:45
  • 1
    I’ve never actually used that so I would actually be taught from this question – MrMythical Sep 02 '21 at 16:48
  • Not sure if it has something to do with Mac, but normally it should always return absolute path. Try resolving with path `const path = require('path'); const check = path.resolve(__dirname, './');` – Vinay Sep 02 '21 at 16:52
  • just tried this, and console.log(check) returns `/server/methods/documents` as well :( – Jake Wright Sep 02 '21 at 16:58
  • @MrMythical thats a windows convention, not universal. – Daniel A. White Sep 02 '21 at 17:59

1 Answers1

1

I found this question/answer: Determine project root from a running node.js application

I was able to resolve my issue by getting the root path using process.env.PWD and joining that with the relative path /server/templates/docx/word2016_tpl.docx

aka

const absolutePath = path.join(appRoot, relativePath);
const buff = fs.readFileSync(absolutePath);

Hopefully this works. I've read there are a couple of problems with process.env.PWD such as it does not work on the windows OS. Any comments here would be appreciated!