ctrax
ctrax

Reputation: 55

Node requiring directory rather than specific file

Are these two statements equivalent?

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

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

I thought require needed a module (with our without path) as the parameter. How is it that a directory can be provided and what does the .device do?

Thanks to anyone who can help me understand node.js and javascript better.

Upvotes: 1

Views: 84

Answers (2)

Mayank Soni
Mayank Soni

Reputation: 31

You can use module require-file-directory.

1- Helps to require all the files only with name. No need to give absolute path of files.
2- Multiple files at a time.

Upvotes: 0

James Monger
James Monger

Reputation: 10685

require('..').device requires index.js from the parent directory, and then gets device from that file.

So if you had the following structure:

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

With index.js having the following:

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

Then require("..").device in bar.js would give you "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

So in your example, it will:

  1. look for package.json and get the main property, and then load that if it exists
  2. If step 1 does not exist, it will load index.js if it exists
  3. If step 2 does not exist, it will load index.json if it exists
  4. If step 4 does not exist, it will load index.node if it exists

Upvotes: 4

Related Questions