Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

createRequireFromPath in Node

| Comments

Let us consider an hypothetical scenario where we have project foo with the below directory structure:

1
2
3
4
5
6
7
.
├── index.js
├── lib
│   └── util.js
└── src
    └── component
        └── index.js

Let us say that src/component in dependent on lib/util.js, in current world one would have to do the below to require the util in their component

1
const util = require('../../lib/uitl.js');

The nesting for those realtive paths ../../ gets more complex as the directory structure gets more deeper.

For our rescue the module object of node got an addition of createRequireFromPath method in v10.12.0, which accepts a filenameto be used to construct the relative require function. and return a require function.

This can help in doing the below in our src/component, rather than dealing with relative paths.

1
2
3
const requireLib = require('module').createRequireFromPath('../../lib');

requireLib("util.js");

So, any files in ../../lib can now be just required as requireLib(<absPath>) instead of dealing with relative paths.

The heart of createRequireFromPath looks like:

1
2
3
4
5
6
Module.createRequireFromPath = (filename) => {
  const m = new Module(filename);
  m.filename = filename;
  m.paths = Module._nodeModulePaths(path.dirname(filename));
  return makeRequireFunction(m);
};

Meanwhile, MylesBorins has a proTip for us:

Comments