Skip to content

ModuleLoader

do- edited this page Jul 28, 2024 · 2 revisions

ModuleLoader is wrapper around the standard require function, for a fixed set of directories under given roots with a given filter condition, optionally tracking modification times.

Constructor

const {ModuleLoader} = require ('require-sliced')

const myModuleLoader = new ModuleLoader ({
  dir: {
    root: ['/opt/myProject'], 
//    filter: (str, arr) => arr.at (-2) === 'Content', // **/Content/*
//    live: false,
  },
// ext: '.js',
// watch: false,
})

The only parameter here is a bag of options (see below). For the dir option, a DirList instance is created, other ones are stored as is in eponymous properties.

Options

Name Default value Description
dir a DirList options object.
ext '.js' module files extension
watch false whether to track file modification times

Instance properties

The additional mtimes property contains a nested Map of the following structure:

name1 => Map {
  path11 => mtime11,
  path12 => mtime12,
},
name2 => Map {
  path21 => mtime21,
  ...
},
...

where mtimes are modification times corresponding to paths and names are their base names.

Methods

isModified (name)

Returns true if watch is true and:

  • name is missing from mtimes or
  • dir contains a file ${name}${ext}
    • with path missing from mtimes or
    • with newer modification time.

In the two latter cases, delete (name) is called to invalidate the cache.

Otherwise, returns false.

delete (name)

Deletes name from mtimes and all related entries from require.cache.

This method is called by isModified and is not intended for direct use.

require (name)

Returns an iterator of require results for all file paths in dir with ${name}${ext} base name.

If no file is found, throws an error.

requireAll ()

Scans the entire dir for files ending with ext and returns an iterator of [name, module] pairs where each module is a require result for the file path and name is his base name without this extension.

Clone this wiki locally