我是靠谱客的博主 激昂大侠,这篇文章主要介绍Nodejs总结(一),现在分享给大家,希望可以做个参考。

Nodejs总结(一)

Node.js 是一个基于Chrome JavaScript 运行时建立的一个平台,事件驱动I/O服务端JavaScript环境,基于Google的V8引擎,V8引擎执行Javascript的速度非常快,性能非常好。

  Nodejs创建一个web网站

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const http=require('http'); var server=http.createServer(function (req, res){ switch(req.url){ case '/1.html': res.write("111111"); break; case '/2.html': res.write("2222"); break; default: res.write('404'); break; } res.end(); }); //监听——等着 //端口-数字 server.listen(8080);

操作文件

  修改文件

复制代码
1
2
3
4
5
6
const fs=require('fs'); //writeFile(文件名, 内容, 回调) fs.writeFile("bbb.txt", "1231313", function (err,data){ console.log(err); console.log(data); });

  读取文件

复制代码
1
2
3
4
5
6
7
8
9
const fs=require('fs'); //readFile(文件名, 回调函数) fs.readFile('aaa.txt', function (err, data){ if(err){ console.log('读取失败'); }else{ console.log(data.toString()); } });

  加载页面 

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const http=require('http'); const fs=require('fs'); var server=http.createServer(function (req, res){ //req.url=>'/index.html' //读取=>'./www/index.html' // './www'+req.url var file_name='./www'+req.url; fs.readFile(file_name, function (err, data){ if(err){ res.write('404'); }else{ res.write(data); } res.end(); }); }); server.listen(8080);

  解析url

复制代码
1
参数为false =》字符串, 参数为true =》对象
复制代码
1
2
3
const urlLib=require('url'); var obj=urlLib.parse("http://www.zhinengshe.com/index?a=12&b=5", false); console.log(obj.pathname, obj.query);

获取POST数据

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//post可以接受大量的数据,它是分段发送数据的。 const http=require('http'); const querystring=require('querystring'); http.createServer(function (req, res){ var str=''; //接收数据 //data——有一段数据到达(很多次) var i=0;   req.on('data', function (data){   console.log(`第${i++}次收到数据`);   str+=data; }); //end——数据全部到达(一次)   req.on('end', function (){   var POST=querystring.parse(str);   console.log(POST); }); }).listen(8080);

const http=require('http'); http模块
const fs=require('fs'); 请求文件
const querystring=require('querystring'); 请求post数据
const urlLib=require('url'); 请求get数据

模块化
require——引入
exports——输出
module.exports——批量输出
引入自己的模块——./ ?
对外输出东西——必须加给exports
数据请求
GET数据:
req.url——urlLib.parse(, true)

POST数据接收:POST数据比GET大得多

POST很大——分段
data 一段数据
end 全部到达

 

posted on 2018-12-06 16:42 天然灰 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/tianranhui/p/10077563.html

最后

以上就是激昂大侠最近收集整理的关于Nodejs总结(一)的全部内容,更多相关Nodejs总结(一)内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(81)

评论列表共有 0 条评论

立即
投稿
返回
顶部