Code Monkey home page Code Monkey logo

node-require-all's Introduction

require-all

An easy way to require all files within a directory.

NPM Version NPM Downloads Build Status

Usage

var controllers = require('require-all')({
  dirname     :  __dirname + '/controllers',
  filter      :  /(.+Controller)\.js$/,
  excludeDirs :  /^\.(git|svn)$/,
  recursive   : true
});

// controllers now is an object with references to all modules matching the filter
// for example:
// { HomeController: function HomeController() {...}, ...}

Advanced usage

If your objective is to simply require all .js and .json files in a directory you can just pass a string to require-all:

var libs = require('require-all')(__dirname + '/lib');

Constructed object usage

If your directory contains files that all export constructors, you can require them all and automatically construct the objects using resolve:

var controllers = require('require-all')({
  dirname     :  __dirname + '/controllers',
  filter      :  /(.+Controller)\.js$/,
  resolve     : function (Controller) {
    return new Controller();
  }
});

Alternative property names

If your directory contains files where the names do not match what you want in the resulting property (for example, you want camelCase but the file names are snake_case), then you can use the map function. The map function is called on both file and directory names, as they are added to the resulting object.

var controllers = require('require-all')({
  dirname :  __dirname + '/controllers',
  filter  :  /(.+Controller)\.js$/,
  map     : function (name, path) {
    return name.replace(/_([a-z])/g, function (m, c) {
      return c.toUpperCase();
    });
  }
});

Filtering files

If your directory contains files that you do not want to require, or that you want only a part of the file's name to be used as the property name, filter can be a regular expression. In the following example, the filter is set to /^(.+Controller)\.js$/, which means only files that end in "Controller.js" are required, and the resulting property name will be the name of the file without the ".js" extension. For example, the file "MainController.js" will match, and since the first capture group will contain "MainController", that will be the property name used. If no capture group is used, then the entire match will be used as the name.

var controllers = require('require-all')({
  dirname : __dirname + '/controllers',
  filter  : /^(.+Controller)\.js$/
});

For even more advanced usage, the filter option also accepts a function that is invoked with the file name as the first argument. The filter function is expected to return a falsy value to ignore the file, otherwise a string to use as the property name.

var controllers = requireAll({
  dirname : __dirname + '/controllers',
  filter  : function (fileName) {
    var parts = fileName.split('-');
    if (parts[1] !== 'Controller.js') return;
    return parts[0];
  }
});

Note that empty directories are always excluded from the end result.

node-require-all's People

Contributors

caccialdo avatar danielmoore avatar dougwilson avatar dscape avatar feliun avatar felixge avatar fent avatar gastonelhordoy avatar jmuraski avatar kibertoad avatar leewaygroups avatar skomski avatar thlorenz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-require-all's Issues

Allow .ts files to be found in DEFAULT_FILTER option

Hello ! I'm making a discord bot using discord.js-commando and i migrate my bot to a typescript project

I figure out an issue with [email protected] that is used by discord.js-commando@latest doesn't allow .ts files to be found by default

Maybe you should change the DEFAULT_FILTER regex from /^([^\.].*)\.js(on)?$/ to /^([^\.].*)\.(?:j|t)s(on)?$/

New release with passing map function recursively?

Hi,

Got bitten by a bug in the current release where it doesn't pass the map function down when it recurses directories - looks to be fixed in the current Master, any chance of a release with this fix?

Thanks in advance.

consider updating excludeDirs to match against directories instead of file names

The user interface for this is confusing as excludeDirs, which signature declares it accepts a dirname, is being passed a filename. This seems contradictory and muddles what the contract is supposed to be.

https://github.com/felixge/node-require-all/blob/master/index.js#L16

  function excludeDirectory(dirname) {
    return !recursive ||
      (excludeDirs && dirname.match(excludeDirs));
}

https://github.com/felixge/node-require-all/blob/master/index.js#L38

  files.forEach(function (file) {
    var filepath = dirname + '/' + file;
    if (fs.statSync(filepath).isDirectory()) {

    if (excludeDirectory(file)) return;

Would it not add more clarity to instead allow the regex to match against the directory itself?

That would prevent the need for obfuscated lookbehind/lookahead regex patterns in the filter

thoughts?

Drop older Node.js versions

Considering that there is a plan to do breaking version change for #51, it might be a good time to think about which Node.js version is preferable to support going forward. At the very least subset could be reduced to what express.js is using (super-conservative pragmatic minimum), but maybe we can bump to v4 or v6?..

Could be useful if resolve includes file name.

I've been doing this for a while, extending this module to provide the file name, which is easy because it's already extracted (match[1]), and I don't think it breaks any common use case.

To illustrate why this is useful, this is an example of something I do frequently:

var gulp = require('gulp');

require('require-all')({
    dirname: __dirname + '/src/tasks',
    resolve: function(item, name) {
        gulp.task(name, item.deps, item.task);
    },
});

Example task:

module.exports = {
    deps: [],
    task: function(done) {
        done();
    },
};

So this is very useful when filenames have some semantic meaning, and this small improvement makes this straightforward.

Added a pull request!

Not defined when inside module.exports

I'm trying to require all of my services in the "services" directory

var Services = require('require-all')({
    dirname: __dirname + '/services',
    filter: /^(.+)\.js$/
});

module.exports = async(function (req, res, next){
    .... (my code)
}

If i put a breakpoint on the module.exports line and look at services:

Services 
Object {ServiceOne: Object}

but when I put a breakpoint into my code (inside module.exports) and call that code, I get a ReferenceError

Services
ReferenceError: Services is not defined

Pass in parameters to required files

Is there an option to pass in parameters to all the required files. For example, I have a 'routes' folder

var app = express();
// app.set()...
// etc...

var routes = requireAll(__dirname + '/routes')( app );

Option to flatten results

Currently when "recursive" option is true, results get nested inside directory objects. In many cases you don't actually need that tree structure and flattened result is more convenient to consume.
This should probably come with some mechanism to ensure there are no duplicate filenames.

Bump version tag

Bump version tag to allow latest modifications to be downloaded by npm

add to existing object

any way to pass in an existing object so require-all can add to it rather just using what it returns

How can I pass in a constructor argument?

I'm using express and want to call each library like

server = expressapp(); 

require('route1')(server)
require('route2')(server)

seems like there should be a way with the resolve syntax?

Allow non-recursive require

There should be an option to require folder recursively or non-recursively. Right now it is always recursive requirement of the folder.

Accessing require file question

Suppose I have declare

var jsons = require('require-all')(__dirname + '/json');

and inside the json directory have filename jsonfile1.json, jsonfile2.json.

How could i access jsonfile1?

Similarly, if i have declare

var js = require('require-all')(__dirname + '/js');

and inside the js directory i have js1.js, js2.js, js3.js.
And inside js1, i have export.Module1(), export.Module2().

How could i access export.Module1 in js1.js?

Can't resolve 'fs'

Thanks for creating this useful lib. I am trying to use it in my webpack based project but I get following
error during bundling.

ERROR in ./node_modules/require-all/index.js
Module not found: Error: Can't resolve 'fs' in '/<path>/node_modules/require-all'

Certain files won't get required

For some reason, certain files won't get require'd, although those files themselves are legal.

Ubuntu 16.04 LTS

I don't know how to debug this. The required files are not enumerable.

'use strict';

module.exports = require('require-all')({
	dirname		: __dirname,
	filter		: /^(?!index).+\.js$/,
	map(name, path) {
		console.log(path, name);
	}
});

// Expected to list all included files, but only runs once
for (let idx = 0, keys = Object.keys(module.exports), len = keys.length; idx < len; idx++) {
	let key = keys[idx];
	console.log('GOT MODULE:', key);	// undefined
}

The directory contains the following files:

  • getRequestType.js works
  • getRequestLocations.js does not work, returns undefined
  • getRequestSearches.js works
  • getFakeQuotes.js does not work, returns undefined

The scripts are big, and something causes require-all to skip them.

Assuming a normal require is used internally, the source shouldn't even matter.

Note that all files work fine when importing manually. No errors.
Note that everything works fine using require-dir-all.
Workaround: Use require-dir-all

filter needs a default

var controllers = require('require-all')({
  dirname     :  __dirname + '/controllers',
  excludeDirs :  /^\.(git|svn)$/
});

will return:

{ undefined: OneOfMyControllers }

I'd say the quick fix is:

var match = file.match(options.filter || /^(.+)$/);

I'd love to hear your thoughts.
Thanks.
Joe

filter by dirname?

Would be nice to have the dirname in the filter function. E.g. if you want to match things/*/controllers/*.js

a file with the same name as a directory

When enable recursive option, can not be acquired correctly if there is a file with the same name as the directory

e.g.

foo
--bar.js
--hoge.js
foo.js
buzz.js

any solutions? Thanks in advance!

Dot files and dirs should be ignored

This module tries to include files within .AppleDouble directories which are meta data files created by netatalk when editing files from a mac on an apple share. Should it instead be ignoring all files that start with a dot?

Does not work in strict mode!

Using strict mode (say for using ECMASCRIPT6 classes causes an error.

SyntaxError: Unexpected token =
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:414:25)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:313:12)
    at Function._load (/home/tankerkiller125/clive-servers/websockets/node_modules/pmx/lib/transaction.js:62:21)
    at Module.require (module.js:366:17)
    at require (module.js:385:17)
    at /home/tankerkiller125/clive-servers/websockets/node_modules/require-all/index.js:41:50
    at Array.forEach (native)
    at requireAll (/home/tankerkiller125/clive-servers/websockets/node_modules/require-all/index.js:23:9)
    at Object.<anonymous> (/home/tankerkiller125/clive-servers/websockets/endpoints/chat/index.js:5:35)
    at Module._compile (module.js:435:26)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:313:12)

resolve should also pass in filepath.

It might be useful to also provide the filepath in the callback. In particular, my use case is to recursively loop through folders and build nested objects based on directory structure; passing in the path would help with this.

not able to access few files which are exported

I have a schema like this

const tableName = 'cultures';
const id = {
  type: 'string',
  pattern: '^(([A-Za-z0-9])+\\.)+([A-Za-z0-9])+$',
};
const value = {
  type: 'array',
  minItems: 1,
  items: {
    type: 'string',
    minLength: 1,
  },
};

const language = {
  type: 'string',
  pattern: '^([a-z]{2})$',
};

const demo = {
  type: 'string',
  pattern: '^([a-z]{2})$',
};

const postSchema = {
  type: 'object',
  properties: { value, language, id, demo },
  required: [
    'value',
    'id',
    'language',
    'demo'
  ],
};

const createTableSchema = {
  AttributeDefinitions: [{
    AttributeName: 'id',
    AttributeType: 'S',
  }, {
    AttributeName: 'language',
    AttributeType: 'S',
  }],
  KeySchema: [{
    AttributeName: 'language',
    KeyType: 'HASH',
  }, {
    AttributeName: 'id',
    KeyType: 'RANGE',
  }],
  ProvisionedThroughput: {
    ReadCapacityUnits: 5,
    WriteCapacityUnits: 5,
  },
  TableName: tableName,
};

module.exports.postSchema = postSchema;
module.exports.table = tableName;
module.exports.createTableSchema = createTableSchema;

I am exporting the above objects, in another file I am adding this file using require-all like this

const schema = require('require-all')(__dirname +  '/schema');

The file is getting added, but I am not able to get the exported objects using schema.objName... can you please help me in this regard?

Exclude files

How do you think about having an option to exclude files as well?

In my case I want to exclude a single file, let's say it's a json config which is used by some of the tasks.

I'd need this

require('require-all')({
  excludeFiles:  ['a.json', 'b.json', ...]
});

Best regards

Require-all 0.0.3 package contains hidden .un~ files

Looks like Vim undo files. This is a minor issue. Just one of our tools complained about having backup files in a tree. The files are small tho over 20 times larger than original files :)

Here is my log:

raivo@home:~/Downloads$ npm install require-all
npm http GET https://registry.npmjs.org/require-all
npm http 200 https://registry.npmjs.org/require-all
[email protected] ./node_modules/require-all
raivo@home:~/Downloads$ cd ./node_modules/
raivo@home:~/Downloads/node_modules$ find require-all/ -iname '*un~'
require-all/.index.js.un~
require-all/test/mydir/sub/.config.json.un~
require-all/test/.test.js.un~
require-all/.Readme.md.un~

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.