[英]Node requiring directory rather than specific file
这两个陈述是否相等?
const deviceModule = require('..').device;
const deviceModule = require('../device');
我认为require需要一个模块(没有路径)作为参数。 如何提供目录?.device的作用是什么?
感谢任何可以帮助我更好地理解node.js和javascript的人。
require('..').device
需要从父目录中获取index.js
,然后从该文件中获取device
。
因此,如果您具有以下结构:
- index.js
- /foo
- - bar.js
使用index.js
具有以下内容:
module.exports = {
device: "baz"
};
然后bar.js
require("..").device
会给您"baz"
。
LOAD_AS_DIRECTORY(X)
1. If X/package.json is a file,
a. Parse X/package.json, and look for "main" field.
b. let M = X + (json main field)
c. LOAD_AS_FILE(M)
2. If X/index.js is a file, load X/index.js as JavaScript text. STOP
3. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP
4. If X/index.node is a file, load X/index.node as binary addon. STOP
因此,在您的示例中,它将:
package.json
并获取main
属性,然后将其加载(如果存在) index.js
如果存在) index.json
如果存在) index.node
如果存在) 您可以使用模块require-file-directory。
1-帮助仅要求名称为所有文件。 无需提供文件的绝对路径。
2-一次多个文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.