Skip to content

Instantly share code, notes, and snippets.

@akrawchyk
Created January 15, 2016 14:59
Show Gist options
  • Save akrawchyk/29e5ce5fa16cdf266cb2 to your computer and use it in GitHub Desktop.
Save akrawchyk/29e5ce5fa16cdf266cb2 to your computer and use it in GitHub Desktop.

The problem:

Need to find paths to SCSS assets installed with npm to be used in a gulp script with gulp-sass.

The progress:

const nodeModules = (() => {
  let base = 'node_modules';
  let modulesPath;
  while (true) {
    let stats;
    const upOne = path.resolve(base);
    try {
      stats = fs.statSync(upOne);
      if (stats.isDirectory()) {
        modulesPath = upOne;
        break;
      }
    } catch (e) { /* The node_modules folder wasn't found here */ }
    base = '../' + base;
  }
  return modulesPath;
})();

What I don't like

Node's require() does this for us, see https://nodejs.org/api/modules.html#modules_loading_from_node_modules_folders:

If the module identifier passed to require() is not a native module, and does not begin with '/', '../', or './', then Node.js starts at the parent directory of the current module, and adds /node_modules, and attempts to load the module from that location. Node will not append node_modules to a path already ending in node_modules.

If it is not found there, then it moves to the parent directory, and so on, until the root of the file system is reached.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment