0

I am looking to access a JSON config file that the user would place next to their package.json from a node_module package that I created. Is there a best approach to do this. I tried a relative import but that didn't really work and I am not sure how best to accomplish dynamic imports if the config file doesn't exist because I want to allow it to not exist as well.

Here is how I tried to handle dynamic imports though:

export const overrides = (function () {
    try {
        return require('../../../../../../overrides.json');
    } catch (_err) {
        return null;
    }
})();

Also I tried fs but I get a browser config error I am not sure if that is something else. I should research but I didn't understand the docs around that.

Josh Bowden
  • 892
  • 3
  • 12
  • 28
  • 1
    in entry js code read it as: `global.overrides = Object.freeze(require('./overrides.json'));` and then in another place `return global.overrides` – num8er Dec 29 '21 at 21:56
  • @num8er this all happens in the node package that I created right? How does the ./overrides.json know where that file is relatively? – Josh Bowden Dec 29 '21 at 21:59
  • let's say You have `server.js` at the beginning simply do that global.overrides assignment, after that all modules that will be required by Your app will get that from global object – num8er Dec 29 '21 at 22:01
  • 1
    or create `lib/` folder put there `lib/overrides.js` which will have: `module.exports = Object.freeze(require('../overrides.json'));` and simply in Your app code do `const overrides = require('./lib/overrides');` – num8er Dec 29 '21 at 22:03
  • What if your package is imported by multiple modules in different packages? – GOTO 0 Dec 29 '21 at 22:28

1 Answers1

0

using a library

This worked for me: find-package-json

Basically on any js file who needs the base, home or workspace path, do this:

var finder = require('find-package-json');
var path = require('path');

var f = finder(__dirname);
var rootDirectory = path.dirname(f.next().filename);

rootDirectory will be the location of the folder in which the main package.json exist.

If you want to optimize, get the appRootPath variable at the start of your app and store/propagate the variable to the hole nodejs system.

no libraries

Without any library, this worked for me:

console.log("root directory: "+require('path').resolve('./'));

This will get you the root directory of your nodejs app no matter if you are using npm run start or node foo/bar/index.js

enter image description here

More ways to get the root directory here:

usage

If you achieve to obtain the root directory of your nodejs app and your file is at the package.json level, use this variable like this to locate any file at root level:

rootDirectory+"/overrides.json"
JRichardsz
  • 14,356
  • 6
  • 59
  • 94