0.2.0 • Published 6 years ago

node-require-async v0.2.0

Weekly downloads
9
License
MIT
Repository
github
Last release
6 years ago

node-require-async

Build Status Coverage Status install size

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-async

Example

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
foo

API 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: extension argument in requireAsync. It decides how to compile the content.
  • 0.1.2 (May 25, 2018)

    • Add: support relative path when parentModule is set.
  • 0.1.1 (May 22, 2018)

    • Fix: use files array.
  • 0.1.0 (May 22, 2018)

    • First release.