Javascript node.js 需要文件夹中的所有文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5364928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:53:17  来源:igfitidea点击:

node.js require all files in a folder?

javascriptnode.jsdirectoryrequire

提问by Harry

How do I require all files in a folder in node.js?

如何在 node.js 中要求文件夹中的所有文件?

need something like:

需要类似的东西:

files.forEach(function (v,k){
  // require routes
  require('./routes/'+v);
}};

回答by tbranyen

When require is given the path of a folder, it'll look for an index.js file in that folder; if there is one, it uses that, and if there isn't, it fails.

当 require 指定文件夹的路径时,它会在该文件夹中查找 index.js 文件;如果有,它会使用它,如果没有,它就会失败。

It would probably make most sense (if you have control over the folder) to create an index.js file and then assign all the "modules" and then simply require that.

创建一个 index.js 文件,然后分配所有“模块”,然后简单地要求它可能是最有意义的(如果您可以控制文件夹)。

yourfile.js

你的文件.js

var routes = require("./routes");

index.js

索引.js

exports.something = require("./routes/something.js");
exports.others = require("./routes/others.js");

If you don't know the filenames you should write some kind of loader.

如果您不知道文件名,您应该编写某种加载程序。

Working example of a loader:

加载器的工作示例:

var normalizedPath = require("path").join(__dirname, "routes");

require("fs").readdirSync(normalizedPath).forEach(function(file) {
  require("./routes/" + file);
});

// Continue application logic here

回答by Diogo Cardoso

I recommend using globto accomplish that task.

我建议使用glob来完成该任务。

var glob = require( 'glob' )
  , path = require( 'path' );

glob.sync( './routes/**/*.js' ).forEach( function( file ) {
  require( path.resolve( file ) );
});

回答by Greg Wang

Base on @tbranyen's solution, I create an index.jsfile that load arbitrary javascripts under current folder as part of the exports.

基于@tbranyen 的解决方案,我创建了一个index.js文件,在当前文件夹下加载任意 javascripts 作为exports.

// Load `*.js` under current directory as properties
//  i.e., `User.js` will become `exports['User']` or `exports.User`
require('fs').readdirSync(__dirname + '/').forEach(function(file) {
  if (file.match(/\.js$/) !== null && file !== 'index.js') {
    var name = file.replace('.js', '');
    exports[name] = require('./' + file);
  }
});

Then you can requirethis directory from any where else.

然后你可以require从其他任何地方访问这个目录。

回答by studgeek

Another option is to use the package require-dirwhich let's you do the following. It supports recursion as well.

另一种选择是使用require-dir包,它可以让您执行以下操作。它也支持递归。

var requireDir = require('require-dir');
var dir = requireDir('./path/to/dir');

回答by blented

I have a folder /fields full of files with a single class each, ex:

我有一个文件夹 /fields 充满文件,每个文件都有一个类,例如:

fields/Text.js -> Test class
fields/Checkbox.js -> Checkbox class

Drop this in fields/index.js to export each class:

将其放入 fields/index.js 以导出每个类:

var collectExports, fs, path,
  __hasProp = {}.hasOwnProperty;

fs = require('fs');    
path = require('path');

collectExports = function(file) {
  var func, include, _results;

  if (path.extname(file) === '.js' && file !== 'index.js') {
    include = require('./' + file);
    _results = [];
    for (func in include) {
      if (!__hasProp.call(include, func)) continue;
      _results.push(exports[func] = include[func]);
    }
    return _results;
  }
};

fs.readdirSync('./fields/').forEach(collectExports);

This makes the modules act more like they would in Python:

这使得模块的行为更像它们在 Python 中的表现:

var text = new Fields.Text()
var checkbox = new Fields.Checkbox()

回答by alykoshin

One more option is require-dir-allcombining features from most popular packages.

另一种选择是require-dir-all结合最流行软件包的功能。

Most popular require-dirdoes not have options to filter the files/dirs and does not have mapfunction (see below), but uses small trick to find module's current path.

最流行的require-dir没有过滤文件/目录的选项,也没有map功能(见下文),但使用小技巧来查找模块的当前路径。

Second by popularity require-allhas regexp filtering and preprocessing, but lacks relative path, so you need to use __dirname(this has pros and contras) like:

其次是流行require-all有正则表达式过滤和预处理,但缺乏相对路径,所以你需要使用__dirname(这有优缺点),如:

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

Mentioned here require-indexis quite minimalistic.

这里提到的require-index是相当简约的。

With mapyou may do some preprocessing, like create objects and pass config values (assuming modules below exports constructors):

随着map你可能会做一些处理,比如创建对象,并通过配置值(假设低于出口构造模块):

// Store config for each module in config object properties 
// with property names corresponding to module names 
var config = {
  module1: { value: 'config1' },
  module2: { value: 'config2' }
};

// Require all files in modules subdirectory 
var modules = require('require-dir-all')(
  'modules', // Directory to require 
  { // Options 
    // function to be post-processed over exported object for each require'd module 
    map: function(reqModule) {
      // create new object with corresponding config passed to constructor 
      reqModule.exports = new reqModule.exports( config[reqModule.name] );
    }
  }
);

// Now `modules` object holds not exported constructors, 
// but objects constructed using values provided in `config`.

回答by r3wt

I know this question is 5+ years old, and the given answers are good, but I wanted something a bit more powerful for express, so i created the express-map2package for npm. I was going to name it simply express-map, however the peopleat yahoo already have a package with that name, so i had to rename my package.

我知道这个问题已经有 5 年以上的历史了,给出的答案很好,但我想要更强大的 express,所以我express-map2为 npm创建了包。我打算简单地命名它express-map,但是雅虎的已经有一个同名的包,所以我不得不重命名我的包。

1. basic usage:

1.基本用法:

app.js (or whatever you call it)

var app = require('express'); // 1. include express

app.set('controllers',__dirname+'/controllers/');// 2. set path to your controllers.

require('express-map2')(app); // 3. patch map() into express

app.map({
    'GET /':'test',
    'GET /foo':'middleware.foo,test',
    'GET /bar':'middleware.bar,test'// seperate your handlers with a comma. 
});

controller usage:

控制器用法:

//single function
module.exports = function(req,res){

};

//export an object with multiple functions.
module.exports = {

    foo: function(req,res){

    },

    bar: function(req,res){

    }

};

2. advanced usage, with prefixes:

2.高级用法,带前缀:

app.map('/api/v1/books',{
    'GET /': 'books.list', // GET /api/v1/books
    'GET /:id': 'books.loadOne', // GET /api/v1/books/5
    'DELETE /:id': 'books.delete', // DELETE /api/v1/books/5
    'PUT /:id': 'books.update', // PUT /api/v1/books/5
    'POST /': 'books.create' // POST /api/v1/books
});

As you can see, this saves a ton of time and makes the routing of your application dead simple to write, maintain, and understand. it supports all of the http verbs that express supports, as well as the special .all()method.

如您所见,这节省了大量时间,并使您的应用程序路由变得非常易于编写、维护和理解。它支持express支持的所有http动词,以及特殊.all()方法。

回答by Thorsten Lorenz

One module that I have been using for this exact use case is require-all.

我一直用于这个确切用例的一个模块是require-all

It recursively requires all files in a given directory and its sub directories as long they don't match the excludeDirsproperty.

它递归地要求给定目录及其子目录中的所有文件,只要它们与excludeDirs属性不匹配。

It also allows specifying a file filter and how to derive the keys of the returned hash from the filenames.

它还允许指定文件过滤器以及如何从文件名中导出返回散列的键。

回答by scottnath

I'm using node modules copy-to moduleto create a single file to require all the files in our NodeJS-based system.

我正在使用节点模块复制到模块来创建一个文件,以要求我们基于 NodeJS 的系统中的所有文件。

The code for our utility filelooks like this:

我们的实用程序文件的代码如下所示:

/**
 * Module dependencies.
 */

var copy = require('copy-to');
copy(require('./module1'))
.and(require('./module2'))
.and(require('./module3'))
.to(module.exports);

In all of the files, most functions are written as exports, like so:

在所有文件中,大多数函数都编写为导出,如下所示:

exports.function1 = function () { // function contents };
exports.function2 = function () { // function contents };
exports.function3 = function () { // function contents };

So, then to use any function from a file, you just call:

因此,要使用文件中的任何函数,只需调用:

var utility = require('./utility');

var response = utility.function2(); // or whatever the name of the function is

回答by jtlindsey

Expanding on thisglobsolution. Do this if you want to import all modules from a directory into index.jsand then import that index.jsin another part of the application. Note that template literals aren't supported by the highlighting engine used by stackoverflow so the code might look strange here.

扩展glob解决方案。如果要将目录中的所有模块index.js导入index.js到应用程序的另一部分,然后将其导入,请执行此操作。请注意,stackoverflow 使用的突出显示引擎不支持模板文字,因此此处的代码可能看起来很奇怪。

const glob = require("glob");

let allOfThem = {};
glob.sync(`${__dirname}/*.js`).forEach((file) => {
  /* see note about this in example below */
  allOfThem = { ...allOfThem, ...require(file) };
});
module.exports = allOfThem;

Full Example

完整示例

Directory structure

目录结构

globExample/example.js
globExample/foobars/index.js
globExample/foobars/unexpected.js
globExample/foobars/barit.js
globExample/foobars/fooit.js

globExample/example.js

globExample/example.js

const { foo, bar, keepit } = require('./foobars/index');
const longStyle = require('./foobars/index');

console.log(foo()); // foo ran
console.log(bar()); // bar ran
console.log(keepit()); // keepit ran unexpected

console.log(longStyle.foo()); // foo ran
console.log(longStyle.bar()); // bar ran
console.log(longStyle.keepit()); // keepit ran unexpected

globExample/foobars/index.js

globExample/foobars/index.js

const glob = require("glob");
/*
Note the following style also works with multiple exports per file (barit.js example)
but will overwrite if you have 2 exports with the same
name (unexpected.js and barit.js have a keepit function) in the files being imported. As a result, this method is best used when
your exporting one module per file and use the filename to easily identify what is in it.

Also Note: This ignores itself (index.js) by default to prevent infinite loop.
*/

let allOfThem = {};
glob.sync(`${__dirname}/*.js`).forEach((file) => {
  allOfThem = { ...allOfThem, ...require(file) };
});

module.exports = allOfThem;

globExample/foobars/unexpected.js

globExample/foobars/unexpected.js

exports.keepit = () => 'keepit ran unexpected';

globExample/foobars/barit.js

globExample/foobars/barit.js

exports.bar = () => 'bar run';

exports.keepit = () => 'keepit ran';

globExample/foobars/fooit.js

globExample/foobars/fooit.js

exports.foo = () => 'foo ran';

From inside project with globinstalled, run node example.js

glob已安装的项目内部,运行node example.js

$ node example.js
foo ran
bar run
keepit ran unexpected
foo ran
bar run
keepit ran unexpected