1. Module
http://nodejs.cn/api/modules.html
1. Module concept
In the Node.js module system, each file is treated as an independent module. For example, suppose there is a foo.js
file named :
const circle = require('./circle.js');
console.log(`半径为 4 的圆的面积是 ${circle.area(4)}`);
In the first line, the module in the same directory is foo.js
loaded .foo.js
circle.js
The following is circle.js
the content:
const { PI } = Math;
exports.area = (r) => PI * r ** 2;
exports.circumference = (r) => 2 * PI * r;
circle.js
The module exports area()
and circumference()
functions. By exports
specifying additional attributes on special objects, functions and objects can be added to the root of the module.
2. Module loading
require()
The semantics of Node.js functions are designed to be general enough to support many reasonable directory structures.require()
The core module will always be loaded first. For example,require('http')
always return the built-in HTTP module, even if there is a file with the same name.
2.1. File module loading
If the module is not found by the exact file name, Node.js will try to bring it
.js
and.json
wait for the extension to load.To
'/'
prefix module is the absolute path to the file. For example, filesrequire('/home/marco/foo.js')
will be loaded/home/marco/foo.js
.In
'./'
the module with respect to the call prefixrequire()
relative path of the file containing function.When the file does not start
'/'
with'./'
or'../'
, the module must be a core module or loaded from anode_modules
directory.
2.2. Directory module loading
You can put programs and libraries in a separate directory, and then provide a single entry point to it.
require()
There are three ways to pass the directory as a parameter.
The first way is to create a package.json
file in the root directory and specify a main
module. For example, the package.json
file is similar:
{
"name" : "some-library",
"main" : "./lib/some-library.js"
}
If this is in the ./some-library
directory, it require('./some-library')
will attempt to load ./some-library/lib/some-library.js
.
This is how Node.js processes package.json
files.
If there are no package.json
files in the directory, Node.js will try to load the index.js
or index.node
files in the directory . For example, if the example above did not package.json
file, require('./some-library')
it will attempt to load:
./some-library/index.js
./some-library/index.node
2.3. Node_modules directory loading
If the passed require()
module identifier is not a core module and does not start '/'
with '../'
or './'
, Node.js will start from the parent directory of the current module and try /node_modules
to load the module from its directory. If it is still not found, move to the next parent directory until the root directory of the file system.
For example, if '/home/ry/projects/foo.js'
it is called in the file, require('bar.js')
Node.js will search in the following order:
/home/ry/projects/node_modules/bar.js
/home/ry/node_modules/bar.js
/home/node_modules/bar.js
/node_modules/bar.js
3. Module scope
3.1. __dirname
The directory name of the current module. And __filename
the path.dirname()
same.
Example, /Users/mjr
run from node example.js
:
console.log(__dirname);
// 打印: /Users/mjr
console.log(path.dirname(__filename));
// 打印: /Users/mjr
3.2. __filename
The file name of the current module. This is the absolute path of the current module file.
Example: /Users/mjr
Run from node example.js
:
console.log(__filename);
// 打印: /Users/mjr/example.js
console.log(__dirname);
// 打印: /Users/mjr
3.3. exports
This is a module.exports
shorter form of citation for.
3.4. module
Reference to the current module. module.exports
Used to specify the content exported by a module, that is, the content that can be require()
accessed through .
3.5. require()
Used to import modules,, JSON
or local files. The node_modules
module can be imported from . A relative path may be used (e.g. ./
, , ./foo
, ./bar/baz
) ../foo
into the local module or JSON file, based on the path __dirname
for processing the current working directory or directory names defined.
// 引入本地模块:
const myLocalModule = require('./path/myLocalModule');
// 引入 JSON 文件:
const jsonData = require('./path/filename.json');
// 引入 node_modules 模块或 Node.js 内置模块:
const crypto = require('crypto');
3.6. require.resolve(request)
- request
:
<string> The path of the module to be parsed (relative path) - returns: <string> parsed module path (absolute path)
Use the internal require()
mechanism to query the location (absolute path) of the module. This operation only returns the parsed file name and does not load the module.
Example: When using fs to read files in Node.js, we often encounter the problem of spelling the absolute path of a file (fs processing relative paths are subject to the process execution directory).
The previous method has always been to use the path module and the __dirname variable.
fs.readFileSync(path.join(__dirname, './assets/file.txt'));
Use require.resolve to simplify this process
fs.readFileSync(require.resolve('./assets/file.txt'));
In addition, require.resolve will also check whether the path exists after concatenating the path. If the target path of the resolve does not exist, Cannot find module './file.txt'
an exception will be thrown , and a process of checking whether the file exists (fs.exists) is omitted.
4. The module object
4.1. module.exports
module.exports
The object is Module
created by the system. Exporting an object requires assigning the object to module.exports
.
For example, suppose you are creating a a.js
module named :
const EventEmitter = require('events');
module.exports = new EventEmitter();
// 处理一些工作,并在一段时间后从模块自身触发 'ready' 事件。
setTimeout(() => {
module.exports.emit('ready');
}, 1000);
Then, you can do this in another file:
const a = require('./a');
a.on('ready', () => {
console.log('模块 a 已准备好');
});
4.2. exports
This is a module.exports
shorter form of citation for. module.exports.f = ...
Can be written more concisely as exports.f = ...
Two, path (path)
path
The module provides utilities for handling file paths and directory paths. It can be accessed in the following ways:
const path = require('path');
2.1. path.dirname(path)
path.dirname()
path
The name of the directory returned by the method .
path.dirname('/foo/bar/baz/asdf/quux');
// 返回: '/foo/bar/baz/asdf'
2.2. path.join([...paths])
path.join()
The method uses platform-specific separators to join all the given path
fragments together.
Zero-length path
fragments will be ignored. If the connected path string is a zero-length string, it returns '.'
, indicating the current working directory.
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
// 返回: '/foo/bar/baz/asdf'
path.join('foo', {}, 'bar');
// 抛出 'TypeError: Path must be a string. Received {}'
2.3. path.resolve([...paths])
path.resolve()
The method resolves the sequence of paths or path fragments into absolute paths .
Each parameter is similar to performing an cd
operation in the current directory, executed from left to right, and the last current directory (pwd) is returned!
- If the
path
absolute path has not been generated after processing all the given fragments, then the current working directory is added. - The generated path needs to remove the trailing slash.
- Zero-length
path
fragments will be ignored. - If no incoming
path
fragments, thenpath.resolve()
returns the absolute path to the current working directory.
path.resolve('/foo/bar', './baz');
// 返回: '/foo/bar/baz'
path.resolve('/foo/bar', '/tmp/file/');
// 返回: '/tmp/file'
path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif');
// 如果当前工作目录是 /home/myself/node,
// 则返回 '/home/myself/node/wwwroot/static_files/gif/image.gif'
Reference: small tips: the difference between the use of path join and resolve
Three, process (process)
process
The object is a global variable that provides information about the current Node.js process and controls it. As a global variable, it is always available to Node.js applications and does not need to be used require()
.
3.1. process.env
process.env
The attribute returns an object containing the user's environment.
process.env.foo = 'bar';
console.log(process.env.foo);
// => bar