node-require-async v0.2.0
node-require-async
A require function in node, but an asynchronous one.
This library is built on top of node's builtin Module, so it shares the module cache with require (It is not a wrapper function around builtin require).
Installation
npm install node-require-asyncExample
entry.js
const requireAsync = require("node-require-async")(module);
requireAsync(require.resolve("./foo"))
.then(foo => {
foo.foo();
});foo.js
module.exports = {foo: () => console.log("foo")};$ node entry.js
fooAPI reference
This module exports a single function.
requireAsyncFactory(parentModule?): requireAsync function
You usually pass module as the parentModule parameter. requireAsync would help you setup parentModule.children when a module is loaded.
requireAsync(filename, extension?): moduleExports
Note that this function accepts a filename instead of a moduleId, which means that you have to resolve the moduleId into a filename before passing it to requireAsync:
const filename = require.resolve("./foo"); // "/path/to/foo.js"
requireAsync(filename).then(...)Since builtin require.resolve is blocking, you may need other libraries to resolve filename asynchronously.
If parentModule exists, filename would be resolved as:
path.resolve(path.dirname(parentModule.filename), filename)extension decides how to compile the file. If extension is .json then use JSON.parse. If extension is .js then use module._compile. Default: path.extname(filename).
Changelog
0.2.0 (Jun 26, 2018)
- Add: support JSON files.
- Add:
extensionargument inrequireAsync. It decides how to compile the content.
0.1.2 (May 25, 2018)
- Add: support relative path when
parentModuleis set.
- Add: support relative path when
0.1.1 (May 22, 2018)
- Fix: use files array.
0.1.0 (May 22, 2018)
- First release.