cityvoice
cityvoice

Reputation: 2651

Loading module from directory is different from expectation

According to Nodejs load module's rule, if loading a module from a directory, it will parse package.json first and look for "main" field. But it works unexpectation in my machine. It seems to ignore the main field and always loads the index.js file instead.

directory structure:

node
--node_modules
--test
  --index.js
  --main.js
--package.json
--load.js

package.json

{
  "name": "node",
  "version": "1.0.0",
  "description": "test",
  "main": "main.js"
  ...
}

test/index.js

const text = 'test/index.js'
exports.test = text

test/main.js

const text = 'test/main.js'
exports.test = text 

load.js

const test = require('./test')
console.log(test)  

When I run node load.js, it should output "test/main.js", but the result is "test/index.js"

Upvotes: 0

Views: 38

Answers (1)

AndreasPizsa
AndreasPizsa

Reputation: 1756

If you want node load.js to output test/main.js, require('./main') will do that.

If your code were in the root directory of your project, where package.json is located, and you did require('./'), you would get the result you expect.

That’s because of how node resolves modules.

Background

There are two different concepts at play here:

1) Node Module Resolution Algorithm 2) The main entry point of a package

Node Module Resolution Algorithm

When you do require('./test') without a specific file name, node will attempt to load a file called index.js as part of its Module Resolution Algorithm. The steps of the algorithm are described here (it’s quite a long list of steps, so I won’t copy it here)

This is completely independent from

The main entry point of a package

The main entry in package.json has a different purpose:

The main field is a module ID that is the primary entry point to your program. That is, if your package is named foo, and a user installs it, and then does require("foo"), then your main module’s exports object will be returned.

https://docs.npmjs.com/files/package.json#main

Upvotes: 1

Related Questions