felixge / node-require-all Goto Github PK
View Code? Open in Web Editor NEWAn easy way to require all files within a directory.
License: MIT License
An easy way to require all files within a directory.
License: MIT License
not work:
require('require-all')({
dirname: __dirname,
recursive: true,
filter: /.+\.test\.js$/
});
work
require('require-all')({
dirname: __dirname,
recursive: true,
filter: (fileName) => fileName.match(/.+\.test\.js$/)
});
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)
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?
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'
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.
Need to have ability not to do require-all in directories that does not exist, without manually checks if directory is actually exist. This is required to prevent errors like ENOENT: no such file or directory
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?
any way to pass in an existing object so require-all can add to it rather just using what it returns
If you approve
I'll do a pr for adding a merge option. It would return a "flattened" object for all the files in the directory instead of each file's object having it's own key as it is now. I already have the code so would be an easy add. See my SO post
http://stackoverflow.com/questions/40034688/extending-a-module-when-module-is-using-module-exports
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
?
Currently if there are subfolders in the directory, but there are no files matching the filter, empty object for the subfolder still gets added to the results, even though it is just a noise in such case.
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~
There should be an option to require folder recursively or non-recursively. Right now it is always recursive requirement of the folder.
Its possible. Lets figure out how to do it. :)
Hey there, just wondering if this module (or any of the ones lke it) works in the browser or with browserify/webpack compilation?
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?
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!
Would be nice to have the dirname in the filter function. E.g. if you want to match things/*/controllers/*.js
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
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!
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
worksgetRequestLocations.js
does not work, returns undefined
getRequestSearches.js
worksgetFakeQuotes.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
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.
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?
This module has tests, but no CI, so it's a manual process currently.
@felixge, would you mind logging into Travis CI and enabling this repository? https://travis-ci.org/profile/felixge
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
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)?$/
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 );
fs.readdirSync and fs.statSync functions doesnot exists in require('fs');
Please find alternate
Bump version tag to allow latest modifications to be downloaded by npm
modules[map(name, filepath)] = resolve(require(filepath));
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
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.
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?..
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.