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

需要像这样的东西:

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

当前回答

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

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

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

其他回答

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

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

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

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

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文件,在当前文件夹下加载任意javascript作为导出的一部分。

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

然后,您可以从其他任何地方要求这个目录。

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

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

控制器的使用方法:

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

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

NPM包:https://www.npmjs.com/package/express-map2 Github回购:https://github.com/r3wt/express-map

使用这个函数,你可以要求一个完整的目录。

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