【问题标题】:Node requiring directory rather than specific file需要目录而不是特定文件的节点
【发布时间】:2016-11-14 16:37:22
【问题描述】:

这两个语句是等价的吗?

const deviceModule = require('..').device;

const deviceModule = require('../device');

我认为 require 需要一个模块(我们没有路径)作为参数。如何提供目录以及 .device 的作用是什么?

感谢任何可以帮助我更好地理解 node.js 和 javascript 的人。

【问题讨论】:

  • 我已经编辑了您的问题 - 请不要在标题中添加代码!

标签: javascript node.js syntax


【解决方案1】:

require('..').device 需要父目录中的index.js,然后从该文件中获取device

所以如果你有以下结构:

- index.js
- /foo
- - bar.js

index.js 具有以下内容:

module.exports = {
    device: "baz"
};

那么require("..").device in bar.js 会给你"baz"


Here is the specification for loading a directory:

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

所以在你的例子中,它将:

  1. 查找package.json 并获取main 属性,然后加载该属性(如果存在)
  2. 如果第 1 步不存在,则会加载index.js(如果存在)
  3. 如果第2步不存在,则加载index.json(如果存在)
  4. 如果第4步不存在,则加载index.node(如果存在)

【讨论】:

  • 非常感谢!
  • @ctrax 请不要忘记通过单击向上/向下箭头下方的勾号来接受我的回答。这让其他人知道我的答案就是解决方案,也给了我一些代表作为帮助的奖励。你也得到一些代表接受!每个人都赢了:)
【解决方案2】:

您可以使用模块 require-file-directory。

1- 有助于仅要求所有文件的名称。无需提供文件的绝对路径。
2- 一次多个文件。

【讨论】:

    猜你喜欢
    • 2023-03-17
    • 2014-03-07
    • 2010-12-24
    • 2015-01-11
    • 1970-01-01
    • 2015-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多