node.js学习笔记

# node.js学习笔记

标签(空格分隔): node.js

---

## 一 内置模块学习
### 1. http 模块
```
//1 导入http模块
const http =require('http')
//2 通过http模块的createServer方法创建服务器
let server = http.createServer()
//3绑定监听请求事件
server.on('request',function(req,res){ //第一个参数是请求,第二个是响应
    if(req.url==='/'){
    //res返回结果可以用res.write()但是最后必须接上一个res.end(),只有接收到end后浏览器才会直接拿结果走人

    res.end('这是网站的首页')
    //以上代码等同于
    //res.write('首页')
    //res.end()
    }
})
//4 设置监听端口号
server.listen(3000,function(){
console.log('server-3000 is running')//输出说明浏览器启动成功
}
```
### 2. fs模块
```
//文件数据读取
const fs = require('fs')
//参数1:文件路径 参数2:回调函数,回调函数两个参数一个error一个data,读取成功data为读取内容,err为空,失败data为空,err为错误对象
//注意:这里的data是二进制数,可以用toString方法转为字符串后使用
fs.readFile('./data.txt',function(err,data){
if(err) return
console.log(data.toString())
})

//文件数据写入
fs.writeFile('./data.txt','data',function(err){
    //注意这里的写入文件会覆盖源文件中的内容
    //如果指定目录下无此文件,执行代码会自动创建一个文件
    //err 错误对象,写入成功为null
})
//文件数据追加
fs.appendFile('data.txt','data',function(err){
//这里写入数据会在原有的数据后面追加数据,不会覆盖,当指定文件未找到会自动创建一个该文件
})
```
### 3. path模块
```
const path = require('path')
console.log(path.parse('/index/abc/main.html'))
    // { 
    // root: '/',  根目录
    // dir: '/index/abc', dirname 目录
    // base: 'main.html', basename 文件名(含后缀)
    // ext: '.html', 文件扩展名
    // name: 'main' } 不含后缀的文件名
    //__dirname 代表当前文件所在目录 join方法是在做一个路径的拼接
    path.join(__dirname,'/index.html')
```

## 二 node中的相关插件
### 1. nodemon
+ 作用:
 - 文件更改后自动重启服务器
+ 安装:
 - 安装到全局 npm i nodemon -g
+ 使用:
 - 直接在要使用的目录中运行命令行工具,nodemon app.js
### 2. art-template
+ 作用:
 - 字符串模板
+ 安装:
 - npm i art-template -S
+ 使用:
```
const template = require('art-template')
let string = template(str,{data:list})//第一个参数是字符串模板 第二个参数是数据对象, 返回值是处理好的字符串
/*
字符串模板的语法:
{{each data}}
<li>{{$value}}-----{{$index}}</li>
{{/each}}
*/
```
### 3. express
+ 作用:
 - 封装了node的http模块的功能,使单间服务器变得更简单
+ 安装:
 - 安装到本地 npm i express -S 
+ 使用:
```
const express = require('express')
const app = express()
//开放public目录中的静态资源
app.use('/public/',express.static('./plublic'))
//app.get()处理get请求,默认无法处理post请求,如需POST,必须要安装第三方包才行
app.get('/',function(req,res){
    res.send('首页')
    //res.redirect('/') 重定向功能
})
app.get('/index',function(req,res){
    res.send('还是首页')
})
app.get('/person',function(req,res){
    res.send('<h1>个人中心</h1>')
})
app.get('/more',function(req,res){
    res.send('加载更多')
})
app.listen(3000,function(){})
```
### 4. 在express中使用 art-template 模板
+ 安装:
 - npm i art-template -S
 - npm i express-art-template -S
+ 使用:
```
const express = require('express')

const app = express()
//1. 安装好了art-template 和 express-art-template 后,通过app.engine向response中挂载render方法,app.engine()第1个参数配置处理哪种文件,第2个参数加载art-template
app.engine('html',require('express-art-template'))

app.get('/',function(req,res){
    let items = ['苹果','梨子','橘子','葡萄','桃子']
// 2. 调用render()渲染index.html ,注意:这里的index.html只能放在views文件夹中,然后这里就能直接写文件名了,第1个参数是要渲染的文件,第2个参数要渲染的数据
// 注意:第一个参数不能写路径,默认会去项目中的 views 目录查找该模板文件,Express有一个约定:开发人员把所有的视图文件都放到 views 目录中
    res.render('index.html',{items:items})
})
```
### 5. body-parser
 + 作用:
  - 使express可以获取post请求中的数据
 + 安装:
  - npm i body-parser -S
 + 使用:
```
//1.加载模块
const bodyParser = require('body-parser')
//2.配置bodyParser选项
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
//3.配置完成后req上面就会多一个body的属性,就可以直接调用来获得请求体了
app.post('/post', function (req, res) {
  // req.query 只能拿 get 请求参数
  console.log(req.body)
```
## 6. 抽离路由模块的步骤
+ 1. 创建一个router.js文件
```
//载入express模块
const express = require('express')
//创建一个路由容器
const router = express.Router()
//把路由挂载到路由对象上
router.get('/',function(){
})
//向外暴露路由对象
moudle.express = router
```
+ 2. 在app.js 中引用路由模块
```
//导入路由模块
const router = require('router.js')
//启用路由模块
app.use(router)
```

 

posted @ 2018-12-01 15:23  superjsman  阅读(166)  评论(0编辑  收藏  举报