npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

require-folder

v1.0.0

Published

Recursively require all files within a folder.

Downloads

4,210

Readme

License: MIT Build Status

require-folder

Recursively require all files within a folder.

Installation

$ npm install require-folder

Usage

const requireFolder = require('require-folder');

const result = requireFolder('path/to/target-folder', options);

Example folder structure:

└─ target-folder
   ├─ controller.js
   ├─ foo
   │  ├─ index.js
   │  ├─ bar.js
   │  └─ baz.js
   └─ utils
      ├─ string_utils.js
      └─ array_utils.js

Example results:

result = {
    controller: require('target-folder/controller'),
    foo: require('target-folder/foo'),
    utils: {
        string_utils: require('target-folder/utils/string_utils')
        array_utils: require('target-folder/utils/array_utils')
    }
}

Similar to Node's native require behavior, when a folder has an index.js file it will be the only export for that folder.
When there's no index.js file, all .js files will be required individually.

API


requireFolder(path, options)

Arguments:

  • path - A string, a folder path to require.
  • options - A configuration object. See below.

Return:

An object contains all the required modules in the target folder. The object's structure is generally a representation of the folder.

Options

camelCase

When set to true, converts required modules` names into camelCase style. Any character that is not a letter, a number or an underscore is removed. This enables using js dot notation when using the result object.

Example:

└─ my utils.js
requireFolder('./target-folder', {
    camelCase: true
})
// when `false` (default)
result['my utils']

// when `true`
result.myUtils

normalizeKeys

When set to true, converts dashes and spaces in required modules` names to underscores. This enables using js dot notation when using the result object.

Example:

└─ my utils.js
requireFolder('./target-folder', {
    normalizeKeys: true
})
// when `false` (default)
result['my utils']

// when `true`
result.my_utils

Multiple dashes and spaces in a row are merged into a single underscore.

mapKey

When the camelCase and normalizeKeys options are not enough, you can rename the required modules` by passing a mapper function to the mapKey option. This function gets called with the original entry name (file/folder). The returned string will be used as the new prop name on the result object.

mapKey function is called last, after any other conversion made by camelCase or normalizeKeys.

Example:

└─ target-folder
   ├─ common-utils.js
   ├─ HELLO.js
   └─ WORLD.js
requireFolder('./target-folder', {
    mapKey (name) {
        if (name === 'common-utils') {
            return '$utils';
        }
        else {
            return name.toLowerCase();
        }
    }
})
result = {
    $utils: require('target-folder/common-utils'),
    hello: require('target-folder/HELLO'),
    world: require('target-folder/WORLD'),
}

groups

Alias: group
You can group multiple items under one namespace property.

Example:

└─ target-folder
   ├─ red.js
   ├─ green.js
   ├─ blue.js
   └─ utils.js
requireFolder('./target-folder', {
    group: {
        colors: ['red', 'green', 'blue'],
    },
})
result = {
    utils: require('target-folder/utils'),
    colors: {
        red: require('target-folder/red'),
        green: require('target-folder/green'),
        blue: require('target-folder/blue'),
    }
}

hooks

Sometimes you need even more control over the requiring details. You can use the hooks option for custom requiring certain entries (files or folder).

hooks should be an object that its keys are the names of the entries (files or folders) you would like to customize and values are their hook functions.

hooks keys will match resolved keys, after any conversions made by camelCase, normalizeKeys or mapKey.

Hook Function Arguments

  • requiredModule - the actual exports of the current entry.
  • context - the parent folder context object which current entry will be required into.
  • entryMap - an entry meta data object. Contains its path, type, name, base name & extension (if file) or its entries (if folder).

See map-folder docs for more details about the entryMap object.

Example:

└─ target-folder
   └─ my-file.js
requireFolder('./target-folder', {
    camelCase: true,
    hooks: {
        myFile: (requiredModule, contextObj, entryMap) => {
            if (condition) {
                contextObj.foo = requiredModule;
            }
            else {
                contextObj.bar = requiredModule;
            }
        },
    }
})
result = {
    foo: require('target-folder/my-file'),
    // or
    bar: require('target-folder/my-file'),
}

exclude

A list of file & folder names to skip. See map-folder docs for more details.

└─ target-folder
   ├─ foo.js
   ├─ bar.js
   └─ old-version
      ├─ foo.js
      └─ bar.js
const result = requireFolder('./target-folder', {
    exclude: ['old-version']
});
result = {
    foo: require('target-folder/foo'),
    bar: require('target-folder/bar'),
}

include

A list of file & folder names and extensions to map and require. Folders are only mapped (not required) and extensions are required (currently only supporting .json). See map-folder docs for more details.

└─ target-folder
   ├─ foo.js
   ├─ styles
   │  ├─ reset.css
   │  └─ main.css
   └─ config.json
const result = requireFolder('./target-folder', {
    include: ['styles', '.json']
});
result = {
    foo: require('target-folder/foo'),
    config: require('target-folder/config.json'),  // <-- require json files
    styles: {                                      // <-- only maps folders
        path: 'path/to/target-folder/style',
        isFile: false,
        name: 'styles',
        entries: {
            'reset.css': {
                base: 'reset',
                ext: 'css',
                name: 'reset.css',
                path:'path/to/target-folder/styles/reset.css',
                isFile: true,
            }
            'main.css': {
                base: 'main',
                ext: 'css',
                name: 'main.css',
                path:'path/to/target-folder/styles/main.css',
                isFile: true,
            }
        }
    }
}