您好,登錄后才能下訂單哦!
一、事件
NodeJs是基于事件驅(qū)動(dòng),擁有一個(gè)核心庫(kù):events,使用的時(shí)候需要引入:var events = require('events');
1、util 是一個(gè)Node.js 核心模塊,提供常用函數(shù)的集合,用于彌補(bǔ)核心JavaScript 的功能 過(guò)于精簡(jiǎn)的不足。
var util = require('util');
1、util.inherits
util.inherits(constructor, superConstructor) 是一個(gè)實(shí)現(xiàn)對(duì)象間原型繼承的函數(shù)。
JavaScript 的面向?qū)ο筇匦允腔谠偷?,與常見的基于類的不同。JavaScript 沒有提供對(duì)象繼承的語(yǔ)言級(jí)別特性,而是通過(guò)原型復(fù)制來(lái)實(shí)現(xiàn)的
var events = require('events');
var util = require('util');
var Person = function (name) {
this.name = name;
}
util.inherits(Person,events); //Person繼承了events事件機(jī)制
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');
//結(jié)果:
"C:\Program Files\JetBrains\WebStorm 2018.3.3\bin\runnerw64.exe" "C:\Program Files\nodejs\node.exe" G:\nodeWork\004\001.js
kate
lili
二、讀寫文件(同步,異步)
var fs = require('fs');
var readMe = fs.readFile("readMe.txt", "utf8", function(err, data) {
console.log(data);
});
nodejs執(zhí)行javascript是單線程的,語(yǔ)句還是一行行從上到下執(zhí)行的,但是,nodejs維護(hù)了一個(gè)事件隊(duì)列,readFile的回調(diào)函數(shù)會(huì)push到事件隊(duì)列里面,主線程繼續(xù)從上到下執(zhí)行,當(dāng)主線程空閑的時(shí)候,會(huì)執(zhí)行事件隊(duì)列里面的函數(shù)
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)
三、創(chuàng)建和刪除目錄
創(chuàng)建目錄:mkdir
刪除目錄:rmdir
刪除文件:unlink
以上都是異步方法,同步方法,后面加sync
var 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')
})
})
})
四、流和管道
好處:處理數(shù)據(jù),提高性能
五、http模塊,搭建web 服務(wù)器
1、響應(yīng)純文本給客戶端
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、響應(yīng)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、響應(yīng) HTML 頁(yè)面給客戶端
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.js
var 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 請(qǐng)求發(fā)送數(shù)據(jù)
瀏覽器傳遞數(shù)據(jù)給服務(wù)器
1、通過(guò)地址欄參數(shù) get方法
2、通過(guò)表單 post方法
八、express學(xué)習(xí)
1、GET請(qǐng)求與響應(yīng)
res.send(); send方法可以發(fā)送字符串,也可以發(fā)送json和數(shù)組,express已經(jīng)處理好了
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請(qǐng)求路由參數(shù)(req.params) http://localhost:3000/profile/1164168/xx
路由路徑的參數(shù)是動(dòng)態(tài)的,url里面帶冒號(hào)的參數(shù)都是動(dòng)態(tài)的,可以匹配無(wú)數(shù)種可能
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');
路由路徑是正則表達(dá)式
3、GET請(qǐng)求查詢字符串(req.query) http://localhost:3000/?find=hot
通過(guò)find取值,因?yàn)檫@個(gè)是在地址欄里面的URL,所以都屬于請(qǐng)求的范疇,即都是通過(guò)req來(lái)取值
http://localhost:1818/?name=kate
var 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 請(qǐng)求 和 Postman 工具(模擬表單的請(qǐng)求)
Postman 工具:模擬表單請(qǐng)求,來(lái)推送post請(qǐng)求
body-parser:用于處理post請(qǐng)求的庫(kù),
安裝:npm install body-parser --save
使用:獲取到的信息,都存儲(chǔ)在req.body里面
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded 處理urlencoded,正常的key=value格式數(shù)據(jù)
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json 處理json格式數(shù)據(jù)
app.use(bodyParser.json())
app.post('/',function(req,res){
console.log(req.body);
res.send('post請(qǐng)求');
})
x-www-form-urlencoded:正常的表單提交,不帶文件上傳,還會(huì)對(duì)特殊字符進(jìn)行編碼,帶%的那種
form-data:帶文件上傳的表單提交
頁(yè)面既有keyvalue格式數(shù)據(jù),也有json格式數(shù)據(jù),怎么解析
var express = require('express');
var bodyParser = require('body-parser')
var app = express();
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var 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');
//渲染頁(yè)面到前臺(tái),此頁(yè)面是靜態(tài)頁(yè)面,不能渲染數(shù)據(jù),是express自帶的方法
板模引擎:可以解決渲染數(shù)據(jù)到頁(yè)面的問題
EJS:
安裝:npm install ejs --save
使用:
app.set('views', './views')
app.set('view engine', 'ejs');
然后在根目錄下創(chuàng)建views文件夾,在views文件夾下創(chuàng)建模板文件,如news.ejs
渲染模板文件:res.render();
app.get('/form/:name', function(req, res) {
var person = req.params.name;
res.render('form', { person: person });
});
news.ejs
<h2>
<%= person %>
</h2>
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'); //這個(gè)中間件里面沒有next,后續(xù)的中間件就不會(huì)執(zhí)行了,結(jié)束了請(qǐng)求,頁(yè)面處于掛起狀態(tài),不能正確渲染
})
// app.get('/', function(req, res, next) {
// res.send('ok');
// })
app.listen(3000);
console.log('listening to port 3000');
7、路由中間件
PS:
app.use():表示使用一個(gè)中間件,比如:app.use(bodyParser.urlencoded({ extended: false }))
app.get()、app.post():表示定義一個(gè)請(qǐng)求接口
8、和請(qǐng)求相關(guān)的都放到控制器里面,即controller,和操作數(shù)據(jù)庫(kù)相關(guān)的,放到model里面,和頁(yè)面顯示相關(guān)的,放在view里面
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。