node.js - 需要 ('..' ) 是什么意思?

标签 node.js

我是node.js新手,一直在尝试使用yarn测试一些代码。目前我正在使用以下代码:

const assert = require('assert')
const username = process.env.HDFS_USERNAME || 'webuser'
const endpoint1 = process.env.HDFS_NAMENODE_1 || 'namenode1.lan'
const endpoint2 = process.env.HDFS_NAMENODE_2 || 'namenode2.lan'
const homeDir = `/user/${username}`
const basePath = process.env.HDFS_BASE_PATH || homeDir
const nodeOneBase = `http://${endpoint1}:9870`
const nodeTwoBase = `http://${endpoint2}:9870`

const webhdfs = require('..')

const should = require('should')
const nock = require('nock')

describe('WebHDFSClient', function () {

  const oneNodeClient = new (require('..')).WebHDFSClient({
    namenode_host: endpoint1
  });
})

我从这个仓库得到的:

https://github.com/ryancole/node-webhdfs/blob/master/test/webhdfs.js

当我尝试运行yarn test时,出现以下错误:

Cannot find module '..'
Require stack:
- myrepo/test/lib/hdfs.js
- myrepo/test/tests.js
- myrepo/node_modules/mocha/lib/mocha.js
- myrepo/node_modules/mocha/index.js
- myrepo/node_modules/mocha/bin/_mocha
  Error: Cannot find module '..'

如您所见,require('..') 在代码中使用了几次,我无法弄清楚它的含义。我发现关于 require('../') 的帖子我认为与此不完全相同。

最佳答案

内置的node.js require 函数使用相当复杂的包解析算法。所以有很多因素可能会影响它。

A.默认为 index.js

如果未指定文件名,node.js 隐式需要名为 index.js 的文件。

因此 require("..") 转换为 require("../index.js")

B。 main 包属性。

如果您require位于模块内部并指向模块的根目录,它将从包package.json读取main属性> 并需要那里指定的文件。

因此给出这个包定义(package.json)

{
    "main": "./fileA.js"
} 

require("..") 的调用将被转换为 require("../fileA.js")

资源

Good explanatory blog entry

Official Docs

关于node.js - 需要 ('..' ) 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57205035/

相关文章:

node.js - Nestjs - 在普通 Controller 中连接牛板

node.js - find后确定鉴别器类型的正确方法

javascript - 如何从 $cookies 获取对象?

node.js - Gmail - smtp 错误 421 4.7.0

javascript - NPM 模块 + TypeScript 最佳实践

node.js - 502 错误网关 nginx 谷歌应用程序引擎

node.js - 使用 NodeJS 在 AppFog 上上传文件

Javascript 对象在 Node.js 中行为神秘,但在 jsbin 中工作正常

javascript - BINANCE API - 如何使用用户数据流获取账户信息

javascript - 冲突 dojo.require 和 Socket.io 客户端