ahajib
ahajib

Reputation: 13520

What does require('..') mean?

I am new to node.js and have been trying to test some code using yarn. At the moment I am using the following code:

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
  });
})

that I've got from this repo:

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

and when I try to run yarn test I get the following error:

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 '..'

As you can see, require('..') is used couple of times in the code and I can not figure out what it means. I've found posts on require('../') which I think is not exactly the same as this one.

Upvotes: 2

Views: 936

Answers (1)

Patrick Hollweck
Patrick Hollweck

Reputation: 6725

The inbuilt node.js require function uses a quite complex package resolution algorithm. So there are lots of things that may influence it.

A. Defaulting to index.js

node.js implicitly requires a file named index.js if no file name is specified.

So require("..") translates to require("../index.js")

B. The main package property.

If you require is inside a module and points to the root of the module it will read the main property from the packages package.json and require the file specified there.

So given this package definition (package.json)

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

The call to require("..") will be translated to require("../fileA.js")

Resources

Good explanatory blog entry

Official Docs

Upvotes: 3

Related Questions