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

查看:222
本文介绍了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天全站免登陆