# NodeJS

## Hello World

```javascript
console.log('hello world');
```

## 模块化

`bar.js`：

```javascript
// 当导出的需求为，只是一个对象时，不可以使用exports={xxx}
exports = 'exports~'
```

`foo.js`：

```javascript
var foo = 'foo~';

// 其他模块在引用此模块时，只可以获取到foo模块使用exports导出的成员
exports.foo = foo;
exports.add = function (x, y) {
    return x + y;
}
```

`mbar.js`：

```javascript
module.exports = 'mbar';
```

`main.js`：

```javascript
var foo = require('./foo');
var bar = require('./bar');
var mbar = require('./mbar');

console.log(foo);
console.log(foo.add(1, 2));

console.log(bar); // 所得结果为 {} 而不是'bar'
// 要想只导出一个对象，可以使用module.exports
console.log(mbar)

console.log(module.exports === exports);
```

## 文件目录操作

读取目录：

```javascript
var fs = require('fs');

var path = 'F:/视频/黑马web前端36期/14 nodejs/nodejs资料（7天）/01';
fs.readdir(path, function(err, files){
    if (err) {
        console.error(err);
    } else {
        console.dir(files);
    }
});
```

读取文件：

```javascript
// 浏览器中的 js 没有操作文件的能力
// 但是Node中的 js 具有

// fs 是 file-system 的简写，就是文件系统的意思
// 在node中如果想要进行文件操作，必须要引入核心模块 fs
// fs 模块提供了文件操作的所有API

var fs = require('fs');

// 读取文件
// param1 读取的文件路径
// param2 回调函数, 
// 		包含两个参数 
// 		1.err 读取成功，null  读取失败，err错误对象
// 		2.data 	读取成功，数据
fs.readFile('data/hello.txt', function(){
    
});
```

写入文件：

```javascript
var fs = require('fs');

/**
 * param1: 文件路径 
 * param2: 写入的文件内容
 * param3: 回调
 */
fs.writeFile('data/test.txt', '我是nodejs写入的文件', function(error){
    if (error) {
        console.error('写入失败');
    } else {
        console.log('文件写入成功');
    }
})
```

## 网络编程

### 简单的HTTP服务

```javascript
/**
 * node 提供了一种模块 http， 负责构建web服务器
 */

 // 加载http核心模块
 var http = require('http');

// 获取一个服务器实例
var server = http.createServer();

// 注册request请求事件，当客户端发送请求，会自动触发request请求事件，执行回调函数
server.on('request', function(request, response){
    console.log('收到请求--\n');
    // 判断请求路径
    var reqUrl =   request.url;
    console.log('请求路径：' + reqUrl);
    var data;
    if (reqUrl == '/') {
       data = '<h1>欢迎您，请登陆</h1>';
    } else if (reqUrl == '/login') {
        data = '登陆成功!!';
    } else if (reqUrl == '/goods') {
        var d = {
            flag: '00-00',
            msg: 'success',
            data: {
                products: [
                    {
                        name: '苹果',
                        price: 4.3
                    },{
                        name: '栗子',
                        price: 6.7
                    },{
                        name: '香蕉',
                        price: 2.5
                    }
                ]
            }
        };
        data = JSON.stringify(d);
    } else {
        data = '404 NOT FOUND';
    }
    response.setHeader('Content-Type', 'text/plain; charset=utf-8');
    // 增加相应体中写入数据
    // response.write('xxx');
    // 需要执行end结束请求，并进行响应，否则客户端会一直等待请求
    response.end(data);
});

// 绑定端口号，启动服务器
server.listen(3000, function(){
    console.log('服务器启动成功...端口号3000\n');
});
```

### 使用模板引擎 art-template

```javascript
var tmpl = require('art-template');
var fs = require('fs');

let html = '';

fs.readFile("tmpl/tmpl_test1.html", function (err, data) {
    console.log('---' + data);
    if (err) {
        return console.error('read file error');
    } else {
        // 注意，这里data是二进制数据，必须使用toString转换为字符串
        let h = tmpl.render(data.toString(), {
            name: 'jack',
            age: 18,
            hobby: [
                '学习', '运动', '撩妹'
            ]
        });
        console.log(h);
    }
});
```

`tmpl/tmpl_test1.html`：

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p>大家好，我叫 {{name}}</p>
    <p>今年 {{age}} 岁了</p>
    <p>爱好：
        {{each hobby value index}}
            value
        {{/each}}
    </p>
</body>
</html>
```


---

# 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://yangsx95.gitbook.io/notes/programming-language/javascript/nodejs.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.
