Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/386.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript node.js是否需要文件夹中的所有文件?_Javascript_Node.js_Directory_Require - Fatal编程技术网

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

Javascript node.js是否需要文件夹中的所有文件?,javascript,node.js,directory,require,Javascript,Node.js,Directory,Require,如何要求node.js中文件夹中的所有文件 需要类似于: files.forEach(function (v,k){ // require routes require('./routes/'+v); }}; 当require给定文件夹的路径时,它将在该文件夹中查找index.js文件;如果有,它就使用它,如果没有,它就失败了 创建一个index.js文件,然后分配所有的“模块”,然后简单地要求它,这可能是最有意义的(如果您可以控制文件夹) yourfile.js index.js 如

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

需要类似于:

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

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

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

yourfile.js

index.js

如果你不知道文件名,你应该写一些加载程序

装载机的工作示例:

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

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

// Continue application logic here

另一个选择是使用包,让您执行以下操作。它还支持递归

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

我有一个文件夹/字段,每个文件夹/字段都有一个单独的类,例如:

fields/Text.js -> Test class
fields/Checkbox.js -> Checkbox 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);
这使模块的行为更像Python中的模块:

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

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

// 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);
  }
});

然后您可以从任何其他地方
要求
此目录

我在这个具体用例中使用的一个模块是

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


它还允许指定文件筛选器以及如何从文件名派生返回哈希的键。

如果在目录示例(“app/lib/*.js”)中包含*.js的所有文件:

在目录app/lib中 example.js:

module.exports = function (example) { }
示例-2.js:

module.exports = function (example2) { }
在目录应用程序中创建index.js index.js:

module.exports = require('./app/lib');
我建议使用来完成这项任务

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

glob.sync( './routes/**/*.js' ).forEach( function( file ) {
  require( path.resolve( file ) );
});
我使用创建一个文件来要求基于NodeJS的系统中的所有文件

的代码如下所示:

/**
 * Module dependencies.
 */

var copy = require('copy-to');
copy(require('./module1'))
.and(require('./module2'))
.and(require('./module3'))
.to(module.exports);
在所有文件中,大多数函数都以导出形式编写,如下所示:

exports.function1 = function () { // function contents };
exports.function2 = function () { // function contents };
exports.function3 = function () { // function contents };
因此,要使用文件中的任何函数,只需调用:

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

var response = utility.function2(); // or whatever the name of the function is
还有一个选择是结合最流行软件包的功能

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

其次,受欢迎程度
require all
具有regexp过滤和预处理功能,但缺少相对路径,因此需要使用
\uu dirname
(这有正反两方面)如下:

这里提到的
require index
非常简单

使用
map
可以进行一些预处理,如创建对象和传递配置值(假设下面的模块导出构造函数):


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

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. 
});
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
});
控制器使用:

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

};

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

    foo: function(req,res){

    },

    bar: function(req,res){

    }

};
2。高级用法,带前缀:

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. 
});
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
});
如您所见,这节省了大量时间,并且使应用程序的路由非常容易编写、维护和理解。它支持express支持的所有http谓词,以及特殊的
.all()
方法

  • npm包:
  • github回购:
    • 可以使用:

      • 需要仅具有名称的选定文件或所有文件
      • 不需要绝对路径
      • 易于理解和使用
      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;
      
      完整示例

      目录结构

      globExample/example.js
      globExample/foobars/index.js
      globExample/foobars/unexpected.js
      globExample/foobars/barit.js
      globExample/foobars/fooit.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

      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

      exports.keepit = () => 'keepit ran unexpected';
      
      globExample/foobars/barit.js

      exports.bar = () => 'bar run';
      
      exports.keepit = () => 'keepit ran';
      
      globExample/foobars/fooit.js

      exports.foo = () => 'foo ran';
      
      从带有
      glob
      的项目内部,运行
      node example.js

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

      需要
      路由
      文件夹中的所有文件,并作为中间件应用。无需外部模块

      // require
      const path = require("path");
      const { readdirSync } = require("fs");
      
      // apply as middleware
      readdirSync("./routes").map((r) => app.use("/api", require("./routes/" + r)));
      

      使用此功能,您可能需要一个完整的目录。

      const GetAllModules = ( dirname ) => {
          if ( dirname ) {
              let dirItems = require( "fs" ).readdirSync( dirname );
              return dirItems.reduce( ( acc, value, index ) => {
                  if ( PATH.extname( value ) == ".js" && value.toLowerCase() != "index.js" ) {
                      let moduleName = value.replace( /.js/g, '' );
                      acc[ moduleName ] = require( `${dirname}/${moduleName}` );
                  }
                  return acc;
              }, {} );
          }
      }
      
      // calling this function.
      
      let dirModules = GetAllModules(__dirname);
      

      添加一些说明:当
      require
      给定文件夹的路径时,它将在该文件夹中查找
      index.js
      ;如果有,它就使用它,如果没有,它就失败了。请参阅以获取这方面的真实示例:根目录中有一个
      index.js
      ,它需要
      /lib/mongodb
      ,一个目录
      /lib/mongodb/index.js'
      使该目录中的所有内容都可用。
      require
      是一个同步函数,因此回调没有任何好处。我会改用fs.readdirSync。谢谢,今天遇到了同样的问题,我想“为什么没有require('./routes/*')?”@RobertMartin当您不需要导出任何内容的句柄时,它很有用;例如,如果我只想将一个Express app实例传递给一组将绑定路由的文件。@TrevorBurnham要添加,可以通过此目录中的
      package.json
      更改目录的主文件(即index.js)。类似于:
      {main:'./lib/my custom main file.js'}
      +1 for
      require dir
      ,因为它自动排除调用文件(索引)并默认为当前目录。完美。在npm中还有几个类似的包:requireall、requiredirectory、requiredir和其他。下载量最多的似乎是require all,至少在2015年7月。require-dir是Sean上述评论三年后下载量最多的(但值得注意的是,在撰写本文时它不支持文件排除)
      // require
      const path = require("path");
      const { readdirSync } = require("fs");
      
      // apply as middleware
      readdirSync("./routes").map((r) => app.use("/api", require("./routes/" + r)));
      
      const GetAllModules = ( dirname ) => {
          if ( dirname ) {
              let dirItems = require( "fs" ).readdirSync( dirname );
              return dirItems.reduce( ( acc, value, index ) => {
                  if ( PATH.extname( value ) == ".js" && value.toLowerCase() != "index.js" ) {
                      let moduleName = value.replace( /.js/g, '' );
                      acc[ moduleName ] = require( `${dirname}/${moduleName}` );
                  }
                  return acc;
              }, {} );
          }
      }
      
      // calling this function.
      
      let dirModules = GetAllModules(__dirname);