node.js 我可以用一个 require 语句加载多个文件吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10554241/
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
Can I load multiple files with one require statement?
提问by nico144
maybe this question is a little silly, but is it possible to load multiple .js files with one require statement? like this:
也许这个问题有点傻,但是是否可以使用一个 require 语句加载多个 .js 文件?像这样:
var mylib = require('./lib/mylibfiles');
and use:
并使用:
mylib.foo(); //return "hello from one"
mylib.bar(): //return "hello from two"
And in the folder mylibfiles will have two files:
在文件夹 mylibfiles 中将有两个文件:
One.js
一个.js
exports.foo= function(){return "hello from one";}
Two.js
二.js
exports.bar= function(){return "hello from two";}
I was thinking to put a package.json in the folder that say to load all the files, but I don't know how. Other aproach that I was thinking is to have a index.js that exports everything again but I will be duplicating work.
我想在文件夹中放一个 package.json 说要加载所有文件,但我不知道如何。我正在考虑的其他方法是让 index.js 再次导出所有内容,但我将重复工作。
Thanks!!
谢谢!!
P.D: I'm working with nodejs v0.611 on a windows 7 machine
PD:我正在 Windows 7 机器上使用 nodejs v0.611
回答by freakish
First of all using requiredoes not duplicate anything. It loads the module and it cachesit, so calling requireagain will get it from memory (thus you can modify module at fly without interacting with its source code - this is sometimes desirable, for example when you want to store db connection inside module).
首先 usingrequire不会复制任何东西。它加载模块并缓存它,因此require再次调用将从内存中获取它(因此您可以在不与其源代码交互的情况下动态修改模块 - 这有时是可取的,例如当您想在模块中存储数据库连接时)。
Also package.jsondoes not load anything and does not interact with your app at all. It is only used for npm.
也package.json不会加载任何东西,你的应用程序都没有任何接触。它仅用于npm.
Now you cannot require multiple modules at once. For example what will happen if both One.jsand Two.jshave defined function with the same name?? There are more problems.
现在您不能一次需要多个模块。例如将发生,如果两者是什么One.js,并Two.js具有相同的名称定义的函数?还有更多的问题。
But what you can do, is to write additional file, say modules.jswith the following content
但是你能做的,就是写额外的文件,modules.js用下面的内容说
module.exports = {
one : require('./one.js'),
two : require('./two.js'),
/* some other modules you want */
}
and then you can simply use
然后你可以简单地使用
var modules = require('./modules.js');
modules.one.foo();
modules.two.bar();
回答by chharvey
Yes, you may require a folderas a module, according to the node docs. Let's say you want to require() a folder called ./mypack/.
是的,根据节点文档,您可能需要一个文件夹作为模块。假设您想要 require() 一个名为../mypack/
Inside ./mypack/, create a package.jsonfile with the nameof the folder and a mainjavascript file with the same name, inside a ./lib/directory.
在里面./mypack/,创建一个package.json文件name夹的文件和一个main同名的javascript文件,在一个./lib/目录中。
{
"name" : "mypack",
"main" : "./lib/mypack.js"
}
Now you can use require('./mypack')and node will load ./mypack/lib/mypack.js.
现在您可以使用require('./mypack')并且节点将加载./mypack/lib/mypack.js.
However if you do not include this package.jsonfile, it may still work. Without the file, node will attempt to load ./mypack/index.js, or if that's not there, ./mypack/index.node.
但是,如果您不包含此package.json文件,它可能仍然有效。如果没有该文件,节点将尝试加载./mypack/index.js,或者如果不存在,./mypack/index.node.
My understanding is that this could be beneficial if you have split your program into many javascript files but do not want to concatenate them for deployment.
我的理解是,如果您将程序拆分为许多 javascript 文件但不想将它们连接起来进行部署,这可能会有所帮助。
回答by Cranite
I have a snippet of code that requires more than one module, but it doesn't clump them together as your post suggests. However, that can be overcome with a trick that I found.
我有一段代码需要多个模块,但它并没有像您的帖子建议的那样将它们聚集在一起。但是,这可以通过我发现的一个技巧来克服。
function requireMany () {
return Array.prototype.slice.call(arguments).map(function (value) {
try {
return require(value)
}
catch (event) {
return console.log(event)
}
})
}
And you use it as such
你这样使用它
requireMany("fs", "socket.io", "path")
Which will return
哪个会返回
[ fs {}, socketio {}, path {} ]
If a module is not found, an error will be sent to the console. It won't break the programme. The error will be shown in the array as undefined. The array will not be shorter because one of the modules failed to load.
如果未找到模块,则会向控制台发送错误。它不会破坏程序。错误将在数组中显示为未定义。阵列不会因为其中一个模块加载失败而变短。
Then you can bind those each of those array elements to a variable name, like so:
然后你可以将这些数组元素中的每一个绑定到一个变量名,如下所示:
var [fs, socketio, path] = requireMany("fs", "socket.io", "path")
It essentially works like an object, but assigns the keys and their values to the global namespace. So, in your case, you could do:
它本质上像一个对象一样工作,但将键及其值分配给全局命名空间。所以,在你的情况下,你可以这样做:
var [foo, bar] = requireMany("./foo.js", "./bar.js")
foo() //return "hello from one"
bar() //return "hello from two"
And if you do want it to break the programme on error, just use this modified version, which is smaller
如果您确实希望它在出错时破坏程序,只需使用这个更小的修改版本
function requireMany () {
return Array.prototype.slice.call(arguments).map(require)
}
回答by cssimsek
I was doing something similar to what @freakish suggests in his answerwith a project where I've a list of test scripts that are pulled into a Puppeteer + Jest testing setup. My test files follow the naming convention testname1.js - testnameN.js and I was able use a generator function to require N number of files from the particular directory with the approach below:
我正在做一些类似于@freakish 在他的回答中所建议的项目,其中我有一个测试脚本列表,这些脚本被拉入 Puppeteer + Jest 测试设置。我的测试文件遵循命名约定 testname1.js - testnameN.js 并且我能够使用生成器函数通过以下方法从特定目录中要求 N 个文件:
const fs = require('fs');
const path = require('path');
module.exports = class FilesInDirectory {
constructor(directory) {
this.fid = fs.readdirSync(path.resolve(directory));
this.requiredFiles = (this.fid.map((fileId) => {
let resolvedPath = path.resolve(directory, fileId);
return require(resolvedPath);
})).filter(file => !!file);
}
printRetrievedFiles() {
console.log(this.requiredFiles);
}
nextFileGenerator() {
const parent = this;
const fidLength = parent.requiredFiles.length;
function* iterate(index) {
while (index < fidLength) {
yield parent.requiredFiles[index++];
}
}
return iterate(0);
}
}
Then use like so:
然后像这样使用:
//Use in test
const FilesInDirectory = require('./utilities/getfilesindirectory');
const StepsCollection = new FilesInDirectory('./test-steps');
const StepsGenerator = StepsCollection.nextFileGenerator();
//Assuming we're in an async function
await StepsGenerator.next().value.FUNCTION_REQUIRED_FROM_FILE(someArg);

