Reputation: 55
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
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
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:
package.json
and get the main
property, and then load that if it existsindex.js
if it existsindex.json
if it existsindex.node
if it existsUpvotes: 4