> 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/summary/3/2016-nian-3-yue-14-ri.md).

# 2016年3月14日

## nodejs

### File System

文件系统模块中的异步方法需要一个完成时的**回调函数**作为最后一个传入形参。 回调函数的构成由您调用的异步方法所决定，通常情况下回调函数的第一个形参为返回的错误信息(**err**)。 如果异步操作执行正确并返回，该错误形参则为**null**或者**undefined**。

### http

1. 用户通过浏览器发送一个http的请求到指定的主机
2. 服务器接收到该请求，对该请求进行分析和处理
3. 服务器处理完成以后，返回对应的数据到用户机器
4. 浏览器接收服务器返回的数据，并根据接收到的进行分析和处理

客户端 服务端

由客户端发送一个http请求到指定的服务端 -> 服务端接收并处理请求 -> 返回数据到客户端

```javascript
var http=require('http');
var server=http.createServer();

server.listen(8080);

console.log(server.address());

//Output
//{ address: '::', family: 'IPv6', port: 8080 }
```

```javascript
//加载一个http模块
var http = require('http');
//通过http模块下的createServer创建并返回一个web服务器对象
var server = http.createServer();

server.on('error', function(err){
    console.log(err);
});

server.on('listening', function() {
    console.log('listening...');
})

server.on('request', function(req, res) {
    console.log('有客户端请求了');

    //console.log(req);

    //res.write('hello');

    res.setHeader('miaov', 'leo');

    res.writeHead(200, 'miaov', {
        //'content-type' : 'text/plain'

        'content-type' : 'text/html;charset=utf-8'
    });

    res.write('<h1>hello</h1>');

    res.end();

})

server.listen(8080, 'localhost');

//console.log(server.address());
```

* var http=require('http');
* var server=http.createServer(\[requestListener])
  * 创建并返回一个HTTP服务器对象
  * requestListener：监听到客户端连接的回调函数
* server.listen(\[port,\[hostname],\[backlog],\[callback]])
  * 监听客户端连接请求，只有当调用listen方法以后，服务器才开始工作
  * port：监听的端口
  * hostname：主机名（IP/域名）
  * backlog：连接等待队列的最大长度
  * callback：调用listen方法并成功开启监听以后，会触发一个listen事件，callback将作为该事件的执行函数。
* listening事件：当server调用listen方法并成功开始监听以后触发的事件。
* error事件：当有客户端发送请求道该主机和端口的请求的时候触发
  * 参数request：http.IncomingMessage的一个实例，通过他我们可以获取到这次请求的一些信息，比如信息，数据等。
  * 参数response：http:http.ServerResponse的一个实例，通过他我们可以向该请求的客户端输出返回的响应。
