require('..')是什么意思?

时间:2019-07-25 15:01:46

标签: 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('../')上发现了与我的帖子不完全相同的帖子。

1 个答案:

答案 0 :(得分:3)

内置的node.js require函数使用非常复杂的包解析算法。因此,有很多因素可能会影响它。

A。默认为index.js

如果未指定文件名,则

node.js隐式需要一个名为index.js的文件。

所以require("..")转换为require("../index.js")

B。 main包属性。

如果require位于模块内部并指向模块的根,它将从软件包main中读取package.json属性,并要求在其中指定文件。

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

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

require("..")的呼叫将转换为require("../fileA.js")

资源

Good explanatory blog entry

Official Docs