2

Current code in /config/index.js

const options = (require('js-yaml')).safeLoad(
  (require('fs')).readFileSync(`./config/default-config.yaml`, "utf8"));

module.exports = options;

Works fine. Until I publish and use it in my other project. Then it's unable to find the file (naturally) as ./config/default-config.yaml doesn't exist in that project.

The only option I can think of involves checking to see if the file exists at that path, then trying to load it from node_modules/@company/alpha-gamma/config/default-config.yaml. This seems really hacky.

The config object is large, 200+ keys. I don't think it belongs in the code.

What's the best solution for loading a file that exists inside your module? I need to be able to load it for unit tests before publishing and load it at runtime when the library is required by another module.

Maybe the best alternative is to use json since I can then use the require module to load it in, instead of fs.

jcollum
  • 43,623
  • 55
  • 191
  • 321
  • I had intended to point you to this- it seems similar. https://stackoverflow.com/questions/13051961/proper-way-to-reference-files-relative-to-application-root-in-node-js – Robert Hartshorn Aug 22 '17 at 22:59
  • don't know why but `__dirname` has always seemed like a hacky trick to me -- like something they meant to remove years ago – jcollum Aug 22 '17 at 23:06
  • 1
    I don't disagree with that at all. I was rather surprised I didn't find more immediately on this topic. – Robert Hartshorn Aug 22 '17 at 23:26
  • 1
    Looks like that did it. That `__dirname` just seems so not-Node-ish; seems like a Ruby/Python-ism instead. It's incongruous. – jcollum Aug 22 '17 at 23:34
  • A bittersweet victory. Now you are on the proper path to heroism. – Robert Hartshorn Aug 22 '17 at 23:36
  • 1
    Write it up, you deserve the answer credit. – jcollum Aug 23 '17 at 00:29
  • 1
    Updated my answer three years later. I misinformed you, I believe the proper answer is avoiding `__dirname` and utilizing `process.cwd()` instead. Your reservations on using it were correct. – Robert Hartshorn Feb 02 '20 at 01:39

1 Answers1

1

While I originally suggested utilizing __dirname as a valid option, I was wrong. Calling process.cwd() to fetch the application root and building the path off of that is the best approach.

As documented here: Proper way to reference files relative to application root in Node.JS