0

I'm writing a CLI tool in Node and I'd like it to be configurable by a config file when it's used by a consumers project. Pretty similar to how es-lint's .eslintrc or babel .bablerc works.

consumer-app
  node_modules
    my-cli-tool
      index.js ← my tool
  .configfile ← configuration file for the cli tool
  package.json

These files are usually placed at the root of the project and sometimes you can have multiple config files at different levels of the file tree.

consumer-app
  sub-directory
    .configfile ← another configuration file for this sub-dir
  node_modules
    my-cli-tool
      index.js ← my tool
  .configfile ← configuration file
  package.json

What's the overall architecture of building something similar? I can have my module look for its config file - but I'm having a hard time locating those config files or the root directory of a project because that's most likely where they're going to be.

Waseem
  • 651
  • 1
  • 5
  • 15

1 Answers1

0

I was able to resolve this problem by looking the config file up the tree of a given __dirname.

This following method takes a filename and scans up the tree each directory the __dirname is part of until it finds the given file. This also makes it possible for each directory to have its own config file.

function getRootFile(filename) {
  return new Promise((resolve, reject) => {
    let lastFound = null;
    let lastScanned = __dirname;
    __dirname.split('/').slice(1).reverse().forEach(dir => {
      const parentPath = path.resolve(lastScanned, '../');
      if (fs.existsSync(path.join(parentPath, filename))) {
        lastFound = path.join(parentPath, filename);
      }
      lastScanned = parentPath;
    });
    resolve(lastFound);
  });
}

async function main() {
  const configPath = getRootFile('.myapprc')
}

This is only a proof-of-concept so it isn't perfect, but something to demonstrate what I'm trying to achieve.

Waseem
  • 651
  • 1
  • 5
  • 15