node.js 需要文件夹中的所有文件? [英] node.js require all files in a folder?

查看:33
本文介绍了node.js 需要文件夹中的所有文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

需要类似的东西:

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

推荐答案

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

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.

创建一个 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.

yourfile.js

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

index.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.

加载器的工作示例:

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

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

// Continue application logic here

这篇关于node.js 需要文件夹中的所有文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆