banner
Nodejs

nodejs

Scroll down

Nodejs

fs模块

fs.readFile()方法

  • fs.readFile()方法的语法格式
    fs.readFile(path[,options],callback)

参数1:必选参数,字符串,读取文件的路径
参数2:可选参数,表示以什么编码格式来读取文件
参数3:必选参数,文件读取完成后,通过回调函数拿到读取结果

1
2
3
4
5
6
7
8
判断读取是否成功
const fs = require('fs');
fs.readFile('./test.txt','utf-8',function(err,result){
if(err){
return console.log('读取失败' + err.message);
}
console.log('读取完成:' + result);
})

fs.writeFile()向指定文件写入内容 语法格式

fs.writeFlie(file,data[,options],callback)
参数1:必选参数,指定文件路径
参数2:必选参数,要写入的内容
参数3:可选参数,以什么格式写入,默认utf-8
参数4:必选参数,文件写入完成后的回调函数

__dirname表示当前文件所在路径

path.join()动态拼接路径

path.join()方法将多个路劲片段拼接成一个路径字符串
path.join([…paths]) 片段中’../‘会抵消前一个路径

path.basename()方法,从路径字符串中解析出文件名

path.basenmae()方法可以获取路径中的最后一个部分
path.basenanme(path[,ext]) 第一个参数是必选参数,表示一个路径 第二个参数是可选参数,表示文件扩展名

path.extname()可以获取路径中的扩展名部分

http模块

创建Web服务器

1
2
3
4
5
6
7
8
9
10
11
12
const http = require('http');

// 创建web服务器实例
const server = http.createServer();
// 为web服务器实例绑定request对象,监听客户端的请求
server.on('request',function(req,res){
console.log('有人访问服务端了');
})
// 启动服务器
server.listen(8080,function(){
console.log('服务已启动 服务器:127.0.0.1:8080');
})

req请求对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const http = require('http');

const server = http.createServer();
server.on('request',(req) => {
// req是请求对象,包含了与客户端相关的数据和属性
// req.url 是客户端请求的URL地址
const url = req.url;
// req.method 是客户端请求的method类型
const method = req.method;
const str = `你的客户端请求地址是${url},你的请求类型是${method}`;
console.log(str);
});
server.listen(80,() => {
console.log('服务启动在127.0.0.1:80');
})

res响应对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const http = require('http');
const server = http.createServer();
server.on('request',(req,res) => {
const url = req.url;
const method = req.method;
const str = `客户端请求地址是${url},请求方法是${method}`;
// res.end()方法,向客户端响应一些内容
// 当调用res.end()方法向客户端发送中文内容时会出现乱码,需要手动设置内容的格式编码
// 为防止中文乱码,需设置响应头Content-Type的值为text/html;charset=utf-8
res.setHeader('Content-Type','text/html;charset=utf-8');
res.end(str)
console.log('有人发起了请求');
});
server.listen(80,() => {
console.log('服务已经启动 http://127.0.0.1:80');
})

实现服务器案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const http = require('http');
const fs = require('fs');
const path = require('path');

const server = http.createServer();
server.on('request', (req, res) => {
const url = req.url;
let fpath = ''
if(url === '/'){
fpath = path.join(__dirname,'./clock/index.html')
}else{
fpath = path.join(__dirname, '/clock', url);
}
// const fpath = path.join(__dirname, '/clock', url);

fs.readFile(fpath, (err, dataStr) => {
if (err) return res.end('404 not found' + err.message)
res.end(dataStr);
})
});
server.listen('8080', () => {
console.log('服务已启动:http://127.0.0.1:8080');
})

express

express创建基本Web服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// 导入express
const express = require('express')
// 创建web服务器
const app = express();
// 监听客户端的get和post请求,并响应客户端具体内容
app.get('/user',(req,res) => {
// 调用express提供的res.send()方法,向客户端响应一个JSON对象
res.send({
name: 'zangsan',
age:'17',
gender:'20'
})
});
app.post('/user',(req,res) => {
res.send('请求成功!')
})

app.get('/',(req,res) => {
// 通过req.query可以获取到客户端发送过来的查询参数,默认情况下,req.query是一个空对象
res.send(req.query)
})
app.get('/user/:id',(req,res) => {
// req.params 是动态匹配到的URL参数,默认是一个空对象
res.send(req.params);
})
// 启动服务器
app.listen(8080,() => {
console.log('服务已启动:http://127.0.0.1:8080');
})

静态资源托管函数

1
2
3
4
5
6
7
8
9
10
11
// 使用express.static()函数,对外提供静态资源
const express = require('express');
const app = express();
// 调用express.static(),对外提供静态资源
app.use(express.static('./clock'));
// 需要托管多个静态文件时,要多次调用express.static()函数
// 如果希望托管的静态资源访问路径之前,挂载路径前缀:
app.use('/clock',express.static('./clock'));
app.listen(8080,() => {
console.log('http://127.0.0.1');
})

express路由

1
2
3
4
5
6
7
const express = require('express');
const app = express();
app.get('/',(req,res) => {res.send('hello')});
app.post('/',(req,res) => {res.send('Post Requset')});
app.listen(80,() => {
console.log('服务启动:http://127.0.0.1:80');
})

router

1
2
3
4
5
6
7
const express = require('express');
const router = express.Router();

router.get('/user',(req,res) => {res.send('get user')});
router.post('/user/add',(req,res) => {res.send('add new user')});

module.exports = router;

中间件

客户端发送的任何请求,到达服务器之后都会触发的中间件,叫做全局生效的中间件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const express = require('express');
const app = express();

// 定义一个中间件
/* const mw = function (req,res,next) {
console.log('这是一个最简单的中间件函数');
next();
}
// 客户端发送的任何请求,到达服务器之后都会触发的中间件,叫做全局生效的中间件。
// 将mw注册为全局生效的中间件
app.use(mw); */

// 中间件简化写法
app.use((req,res,next) => {
console.log('这是一个简单的中间件函数');
next();
})
app.get('/',(req,res) => {res.send('home page');})
app.get('/user',(req,res) => {res.send('user page');})
app.listen(8080,() => {
console.log('listen@ http://127.0.0.1');
})

局部生效中间件

1
2
3
4
5
6
7
8
9
10
11
12
13
const express = require('express');
const app = express();
const mw = function (req,res,next) {
console.log('这是局部生效的中间件');
next();
};
app.get('/',mw,(req,res) => {
res.send('局部生效')
});

app.listen(80,() => {
console.log('服务已启动');
})

错误级别中间件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 导入express
const express = require('express')
// 创建web服务器
const app = express();
app.get('/',(req,res) => {
throw new Error('服务器内部发生异常');
});
// 错误级别中间件,捕获整个项目异常,防止项目崩溃
app.use((err,req,res,next) => {
console.log('发生了错误:'+ err.message);
res.send(err.message)
})
// 启动服务器
app.listen(8080,() => {
console.log('服务已启动:http://127.0.0.1:8080');
})

express编写接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 导入express
const express = require('express')
// 创建web服务器
const app = express();
// 配置解析表单数据的中间件
app.use(express.urlencoded({extended : false}));
// 导入路由模块
const router = require('./11apiRouter');
// 注册路由
app.use('/user',router)

// 启动服务器
app.listen(8080,() => {
console.log('服务已启动:http://127.0.0.1:8080');
})

apiRouter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const express = require('express');
const router = express.Router();

router.get('/get',(req,res) => {
// 通过req.query获取客户端发送的查询字符串数据
const query = req.query;
// 调用res.send()方法,向客户端响应处理结果
res.send({
status:0,
mag:'请求成功',
data:query
})
});
router.post('/post',(req,res) => {
// 通过req.body获取请求体中的URL-encode格式数据
const body = req.body;
res.send({
sattus:0,
msg:'请求成功',
data:body
})})
module.exports = router;

cors解决跨域

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 导入express
const express = require('express')
// 创建web服务器
const app = express();

// 配置解析表单数据的中间件
app.use(express.urlencoded({extended : false}));

// 在cors之前配置jsonp接口
app.get('/api/jsonp',(req,res) => {
const fncName = req.query.callback;
const data = {name:'zs',age:'8'};
const scriptStr = `${fncName}(${JSON.stringify(data)})`;
res.send(scriptStr);
})
// 在路由模块之前,导入cors中间件,解决跨域问题
const cors = require('cors');
app.use(cors());

// 导入路由模块
const router = require('./11apiRouter');
// 注册路由
app.use('/user',router);
// 启动服务器
app.listen(8080,() => {
console.log('服务已启动:http://127.0.0.1:8080');
})
其他文章
cover
css伪类
  • 23/04/15
  • 11:19