本文共 7656 字,大约阅读时间需要 25 分钟。
一、事件
NodeJs是基于事件驱动,拥有一个核心库:events,使用的时候需要引入:var events = require('events');1、util 是一个Node.js 核心模块,提供常用函数的集合,用于弥补核心JavaScript 的功能 过于精简的不足。
var util = require('util');1、util.inheritsutil.inherits(constructor, superConstructor) 是一个实现对象间原型继承的函数。JavaScript 的面向对象特性是基于原型的,与常见的基于类的不同。JavaScript 没有提供对象继承的语言级别特性,而是通过原型复制来实现的var events = require('events');var util = require('util');var Person = function (name) { this.name = name;}util.inherits(Person,events); //Person继承了events事件机制var kate = new Person('kate');var lili = new Person('lili');var lucy = new Person('lucy');var persons = [kate,lili,lucy]persons.forEach(function (val) { val.on('speak',function () { console.log(this.name) })})kate.emit('speak');lili.emit('speak');//结果:"C:\Program Files\JetBrains\WebStorm 2018.3.3\bin\runnerw64.exe" "C:\Program Files\nodejs\node.exe" G:\nodeWork\004\001.jskatelili
二、读写文件(同步,异步)
var fs = require('fs');var readMe = fs.readFile("readMe.txt", "utf8", function(err, data) { console.log(data);});
nodejs执行javascript是单线程的,语句还是一行行从上到下执行的,但是,nodejs维护了一个事件队列,readFile的回调函数会push到事件队列里面,主线程继续从上到下执行,当主线程空闲的时候,会执行事件队列里面的函数
var fs = require('fs');fs.readFile('data.txt','utf8',function (err,data) { //异步的事件、IO操作 console.log(data)})var readMe = fs.readFileSync('data.txt','utf8')console.log(readMe)fs.writeFile('writeMe.txt',readMe,function (err,data) { console.log('write finished')})fs.writeFileSync('writeMe.txt',readMe)
三、创建和删除目录
创建目录:mkdir删除目录:rmdir删除文件:unlink以上都是异步方法,同步方法,后面加syncvar fs = require('fs');fs.writeFile('./file/readMe.txt','hello world',function (err,data) { console.log('write done')})/*fs.unlink('./file/readMe.txt',function () { console.log('delete done')})*/fs.mkdir('./file/stuff',function (err,data) { fs.readFile('./file/readMe.txt','utf8',function (err,data) { fs.writeFile('./file/stuff/readMe.txt',data,function (err,data) { console.log('copy successful') }) })})
四、流和管道
好处:处理数据,提高性能五、http模块,搭建web 服务器
1、响应纯文本给客户端
var http = require('http');var server = http.createServer(function (request,response) { console.log('request received'); response.writeHead(200,{'Content-Type':'text/plain'}); response.end('hello from response')})server.listen(3000);console.log('server listen on 3000')
2、响应json给客户端
var http = require('http');var server = http.createServer(function (request,response) { console.log('request received'); response.writeHead(200,{'Content-Type':'application/json'}); var myObj = { name:'xiao', job:'11', age:20 } //response.end('hello from response') response.end(JSON.stringify(myObj))})server.listen(3000);console.log('server listen on 3000')
3、响应 HTML 页面给客户端
var http = require('http');var fs = require('fs');var server = http.createServer(function (request,response) { console.log('request received'); response.writeHead(200,{'Content-Type':'text/html'}); var myReadStream = fs.createReadStream(__dirname + '/index.html'); myReadStream.pipe(response)})server.listen(3000);console.log('server listen on 3000')
六、路由
//server.jsvar http = require('http');var fs = require('fs');function startServer(){ var server = http.createServer(function (request,response) { console.log('request received' + request.url); if(request.url == '/' || request.url == '/home'){ response.writeHead(200,{'Content-Type':'text/html'}); var myReadStream = fs.createReadStream(__dirname + '/index.html'); myReadStream.pipe(response) }else if(request.url == '/about'){ response.writeHead(200,{'Content-Type':'text/html'}); var myReadStream = fs.createReadStream(__dirname + '/about.html'); myReadStream.pipe(response) }else if(request.url == '/name'){ response.writeHead(200,{'Content-Type':'application/json'}); var jsonObj = { name:'kate' } response.end(JSON.stringify(jsonObj)) }else{ response.writeHead(200,{'Content-Type':'text/html'}); var myReadStream = fs.createReadStream(__dirname + '/404.html'); myReadStream.pipe(response) } }) server.listen(3000); console.log('server listen on 3000')}module.exports.startServer= startServer;
七、使用 GET 或 POST 请求发送数据
浏览器传递数据给服务器1、通过地址栏参数 get方法2、通过表单 post方法八、express学习
1、GET请求与响应res.send(); send方法可以发送字符串,也可以发送json和数组,express已经处理好了res.json(); json方法就只能处理json了var express = require('express');var app = express();app.get('/',function(req,res){ res.send('homepage'); var jsonObj = { name:'kate' }; res.send(jsonObj);})app.listen(3000);console.log('listen at port 3000');
2、GET请求路由参数(req.params)
路由路径的参数是动态的,url里面带冒号的参数都是动态的,可以匹配无数种可能var express = require('express');var app = express();app.get('/profile/:id/:name',function(req,res){ res.send('homepage id is ' + req.params.id + ' homepage name is ' + req.params.name )})app.listen(3000);console.log('listen at port 3000');
路由路径是正则表达式
3、GET请求查询字符串(req.query)
通过find取值,因为这个是在地址栏里面的URL,所以都属于请求的范畴,即都是通过req来取值http://localhost:1818/?name=katevar express = require('express');var app = express();app.get('/',function(req,res){ console.log(req.query) //{ name: 'kate' } res.send('index')})app.listen(1818);console.log('listen at port 1818');
4、POST 请求 和 Postman 工具(模拟表单的请求)
Postman 工具:模拟表单请求,来推送post请求body-parser:用于处理post请求的库,安装:npm install body-parser --save使用:获取到的信息,都存储在req.body里面var express = require('express')var bodyParser = require('body-parser')var app = express()// parse application/x-www-form-urlencoded 处理urlencoded,正常的key=value格式数据app.use(bodyParser.urlencoded({ extended: false }))// parse application/json 处理json格式数据app.use(bodyParser.json())app.post('/',function(req,res){ console.log(req.body); res.send('post请求');})x-www-form-urlencoded:正常的表单提交,不带文件上传,还会对特殊字符进行编码,带%的那种form-data:带文件上传的表单提交
页面既有keyvalue格式数据,也有json格式数据,怎么解析
var express = require('express');var bodyParser = require('body-parser')var app = express();// create application/json parservar jsonParser = bodyParser.json()// create application/x-www-form-urlencoded parservar urlencodedParser = bodyParser.urlencoded({ extended: false })app.post('/', urlencodedParser, function(req, res) { console.dir(req.body); res.send(req.body.name);});app.post('/upload', jsonParser, function(req, res) { console.dir(req.body); res.send(req.body.name);});app.listen(3000);console.log('listening to port 3000');
5、板模引擎介绍
res.sendFile( __dirname + '/form.html'); //渲染页面到前台,此页面是静态页面,不能渲染数据,是express自带的方法板模引擎:可以解决渲染数据到页面的问题
EJS:
安装:npm install ejs --save使用:app.set('views', './views')app.set('view engine', 'ejs');然后在根目录下创建views文件夹,在views文件夹下创建模板文件,如news.ejs渲染模板文件:res.render();app.get('/form/:name', function(req, res) { var person = req.params.name; res.render('form', { person: person });});
news.ejs
<%= person %>
6、中间件
var express = require('express');var app = express();app.use('/assets', express.static('public'));app.use(function(req, res, next) { console.log('first middleware'); next(); console.log('first middleware after');})app.use('/home', function(req, res, next) { //中间件可以代替路由的功能,如代替了下面的get方法路由 console.log('second middleware'); res.send('ok'); //这个中间件里面没有next,后续的中间件就不会执行了,结束了请求,页面处于挂起状态,不能正确渲染})// app.get('/', function(req, res, next) {// res.send('ok');// })app.listen(3000);console.log('listening to port 3000');
7、路由中间件
PS:
app.use():表示使用一个中间件,比如:app.use(bodyParser.urlencoded({ extended: false }))app.get()、app.post():表示定义一个请求接口8、和请求相关的都放到控制器里面,即controller,和操作数据库相关的,放到model里面,和页面显示相关的,放在view里面
转载于:https://blog.51cto.com/9161018/2389704