> For the complete documentation index, see [llms.txt](https://note.niefee.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://note.niefee.com/directory-1/module.md).

# module

* [module](/directory-1/module.md#module)
  * [模块简介](https://note.niefee.com/directory-1/pages/-LjTb6evemqq3wlTsYmc#模块简介)

## module

### 模块简介

* 1.首先按照加载的模块的文件名称进行查找
* 2.如果没有找到，则会在模块文件名称后加上.js的后缀，进行查找
* 3.如果还没有找到，则会在文件名称后加上.json的后缀，进行查找
* 4.如果还没有，则会在文件名称后加上.node的后缀，进行查找

> 文件名称 -> .js -> .json -> .node

所有的exports收集到的属性和方法，都赋值给了`module.exports`。当然，这有个前提，就是`module.exports`本身不具备**相同**属性和方法。如果，`module.exports`已经具备一些属性和方法，那么exports收集来的**相同**信息将被忽略。

Nodejs加载模块

```javascript
//导出函数
exports.a = function() {
    console.log();
};

//导出变量
exports.b=10;
```

* 在模块中定义的变量，其作用域范围是当前模块，外部不能够直接的访问
* 如果我们想一个模块能够访问另外一个模块中定义的变量，可以：
  * 1.把变量作为global对象的一个属性，但是这样的做法是推荐
  * 2.使用模块对象 module

```javascript
//使用`global`定义的是全局模块，
global.a = 200;
```

`exports`是`module.exports`的引用。

可以使用`exports.xxx`或者`module.exports.xxx`写入变量或者函数方法等。

不能有`module.exports=xxx`，这样`module.exports`与`exports`的关系就会断开。

`exports`错误引用

```javascript
//bar.js
console.log( module.exports === exports );
var bar = function(){
    console.log(‘it is bar’);
};
console.log( module.exports === exports );
exports = bar;
console.log( module.exports === exports );
//output
//true
//true
//false


//use-bar.js
var bar = require(‘./bar.js’);
bar();  //这个会报错：TypeError: object is not a function
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://note.niefee.com/directory-1/module.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
