# 开发规范 & 基础

Node 应用由模块组成，采用 CommonJS 模块规范。

[CommonJS规范中文版](http://javascript.ruanyifeng.com/nodejs/module.html)

* 每个文件就是一个模块，有自己的作用域。
* 每个模块内部，都有一个`module`对象，代表当前模块。
* `module.exports`属性表示当前模块对外接口
* `require`方法用于加载模块。

  * /表示绝对路径， `./`表示相对于当前文件

  * 如果没有写扩展名，则一次尝试js、json、node扩展名的文件

  * 不写路径则认为是Build-in模块(系统内置模块，比如fs)或者各级node\_modules内的第三方模块

  > require 特性
  >
  > 1.module被加载的时候执行，加载后缓存。（第一次加载执行模块，并缓存，第二次再次加载则不再执行模块）
  >
  > 2.一旦出现某个模块被循环加载，就只输出已经执行的部分，还未执行的部分不会输出。

实例

test1.js

```javascript
console.log('This is a module');

const testVar = 100;

function test(){
  console.log(testVar);
}

module.exports.testVar = testVar;
module.exports.testFn = test;
```

test2.js

```javascript
require('./test1.js');
require('./test1.js');
```

test3.js

```javascript
const mod = require('./test1.js');
console.log(mod.testVar);
mod.testFn();
```

**module.exports 与 exports的区别**

为了方便，Node为每个模块提供一个exports变量，指向module.exports。这等同在每个模块头部，有一行这样的命令。

```javascript
var exports = module.exports;
```

exports 是module.exports 快捷方式，可以向其中添加属性，但是不能改变其指向。

[全局变量](http://nodejs.cn/api/globals.html)

* CommonJS, 使用global对象属性称为全局访问
* [Buffer](http://nodejs.cn/api/buffer.html)、[**process**](http://nodejs.cn/api/process.html)、[console](http://nodejs.cn/api/console.html)
* timer

## 使用 EditorConfig来规范代码风格

官网：<http://editorconfig.org/>

## 代码检查工具

ESLint 是一个开源的 JavaScript 代码检查工具

[中文站](http://eslint.cn/)


---

# Agent Instructions: 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:

```
GET https://xiaoxiami.gitbook.io/nodejs/kai-fa-gui-fan-and-ji-qiao.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
