nodejs 如何手動實現(xiàn)服務(wù)器
這是一個連續(xù)的node學(xué)習(xí)筆記, 本文是第一章, 會持續(xù)更新, 持續(xù)完善
python好用,用久了就會把人的脾氣養(yǎng)起來, nodejs不好用, 但效率很好, 也能徹底治好你的壞脾氣
nodejs的回調(diào)是我用過的最蛋疼的編程方式之一, 但也足夠巧妙, 學(xué)好node, 對一個程序員而言, 也是一個穩(wěn)賺不賠的買賣
廢話不多說, 上代碼
1. 完成環(huán)境的搭建, 運行一個正則,提取字符串中的數(shù)字
let numRe = /\d+/g;
console.log("123dsgfas 12434 sdfasdf234dagsdfg".match(numRe));
nodejs的語法和瀏覽器js的語法非常接近, 安裝好node后, 可以寫個正則, 測試一下環(huán)境是否安裝成功, 通過atom的script插件容易造成端口占用,建議學(xué)習(xí)過程中用命令行工具執(zhí)行node腳本, 如 node HelloWorld.js
2. http模塊開啟一個服務(wù)
const http = require("http")
//開啟一個監(jiān)聽8080端口的靜態(tài)服務(wù)
http.createServer(function(req, res){
console.log("==>", req.url);
if (req.url === "/1.html"){
res.write("you have request 1.html");
}else if (req.url === "/2.html") {
res.write("you have request 2.html");
}else{
res.write("404(page not found)");
}
res.end();
}).listen(8080)
開啟服務(wù),分三步:
第一步: 引入模塊
第二步: 調(diào)用模塊http.createServer
第三步: 監(jiān)聽端口http.createServer(function(req, res){}).listen(8080)
3. fs模塊讀寫文件
const fs = require("fs");
// 寫入文件
fs.writeFile("HelloWorld.txt", "HelloWorld HelloNode", function(err){
if(err){
console.log(err);
}
// 讀取剛剛寫入的數(shù)據(jù)
else{
fs.readFile("HelloWorld.txt", function(err, data) {
if(err){
console.log(err);
}else{
console.log(data.toString());
}
})
}
})
簡單讀寫文件非常簡單, 與其它編程語言類似, 把調(diào)用方法背過就可以了
4.實現(xiàn)一個靜態(tài)http服務(wù)器
const http = require("http");
const fs = require("fs")
http.createServer(function(req, res){
// 打開 www/ 目錄下的文件
fs.readFile("./www/"+req.url, function(err, data) {
if(err){
console.log(err);
res.write("404");
res.end();
}else{
console.log(data.toString())
res.write(data);
res.end();
}
})
}).listen(8080)
通過了讀取 www/ 目錄下的文件, 實現(xiàn)了靜態(tài)資源服務(wù)器
5.獲取get數(shù)據(jù)
const http = require("http");
const url = require("url");
http.createServer(function(req, res){
let reqObj = url.parse(req.url, true)
let urlPath = reqObj.path;
let urlData = reqObj.query;
let log = "==>urlPath:" + urlPath +"==>>urlData:"+ JSON.stringify(urlData);
console.log(log);
res.write(log);
res.end();
}).listen(6060)
解析get請求的參數(shù)
6.獲取post數(shù)據(jù)
const http = require("http");
const querystring = require("querystring");
http.createServer(function(req, res){
let dataStr = '';
let i = 0;
req.on("data", function(data){
dataStr+=data;
console.log(`第${i++}次收到數(shù)據(jù)`);
})
req.on("end", function(){
console.log("end");
let parseData = querystring.parse(dataStr);
console.log("parseData:", parseData);
res.write(new Buffer(dataStr, "utf8"));
res.end();
})
}).listen(8800)
解析post請求的參數(shù)
小結(jié): 用已有知識 實現(xiàn)簡單的服務(wù)器程序
const http = require("http");
const fs = require("fs");
const querystring = require("querystring");
/*
*1. 訪問www內(nèi)的靜態(tài)資源
*2. 解析get請求, 并保存到serverLog.txt
*3. 解析post請求serverLog.txt
*/
// 獲取當(dāng)前時間
function getNowDate(){
let dt = new Date();
let year = dt.getFullYear();
let month = dt.getMonth();
let day = dt.getDate();
// 將月份加1
month = month + 1;
// 將月份補齊到兩位
if (month <= 9){
month = "0" + month;
}
// 將日補齊到兩位
if (day <= 9){
day = "0" + day;
}
let hour = dt.getHours();
let minutes = dt.getMinutes();
let seconds = dt.getSeconds();
return year+"-"+month+"-"+day+"-"+hour+"-"+minutes+"-"+seconds;
}
http.createServer(function(req, res){
// 1. 嘗試訪問www下的靜態(tài)資源
fs.readFile("./www"+req.url, function(err, data){
if(err){
//2. 解析請求的參數(shù), 并保存到log
if(req.method === "GET"){
console.log("收到了GET請求")
let getData = querystring.parse(req.url.split("?")[1]);
console.log("獲得的get數(shù)據(jù)為==>",getData);
fs.writeFile("./serverLog.txt", getNowDate()+"\n"+JSON.stringify(getData)+"\n", {flag: 'a'},function(err){
if(err){
console.log(err);
console.log("GET數(shù)據(jù)保存至log出錯");
}
});
}else if (req.method == "POST") {
console.log("收到了POST請求")
let tmpData = ''
req.on("data", function(data){
tmpData+=data;
});
req.on("end", function(){
let postData = querystring.parse(tmpData);
console.log("獲得的post數(shù)據(jù)為==>", postData);
fs.writeFile("./serverLog.txt",getNowDate()+"\n"+JSON.stringify(postData)+"\n", {flag: 'a'},function(err){
if(err){
console.log(err);
console.log("POST數(shù)據(jù)保存至log出錯");
}
});
})
}
res.write("404");
res.end();
}else{
res.write(data);
res.end();
}
})
}).listen(8000)
python測試腳本
import requests
requests.get("http://127.0.0.1:8000/?name=zhaozhao&age=18&method=GET")
requests.post("http://127.0.0.1:8000", data={"name": "zhaozhao", "age": 18, "method": "POST"})

熟悉了nodejs回調(diào)機制, 用原生nodejs寫服務(wù)器程序是一件很有效率的事情 , 測試腳本還是requests好用!
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- nodejs express配置自簽名https服務(wù)器的方法
- 通過nodejs 服務(wù)器讀取HTML文件渲染到頁面的方法
- 利用nodeJs anywhere搭建本地服務(wù)器環(huán)境的方法
- NodeJs搭建本地服務(wù)器之使用手機訪問的實例講解
- nodeJS服務(wù)器的創(chuàng)建和重新啟動的實現(xiàn)方法
- nodejs搭建本地服務(wù)器輕松解決跨域問題
- nodejs實現(xiàn)的簡單web服務(wù)器功能示例
- nodejs簡單實現(xiàn)TCP服務(wù)器端和客戶端的聊天功能示例
- nodejs創(chuàng)建簡易web服務(wù)器與文件讀寫的實例
相關(guān)文章
Nodejs中使用puppeteer控制瀏覽器中視頻播放功能
本項目主要功能為在瀏覽器中自動播放視頻,并且實現(xiàn)音量控制,快進快退,全屏控制,播放暫??刂频裙δ堋odejs中使用puppeteer控制瀏覽器中視頻播放功能感興趣的朋友跟隨小編一起看看吧2019-08-08
基于Node.js的強大爬蟲 能直接發(fā)布抓取的文章哦
基于Node.js的強大爬蟲能直接發(fā)布抓取的文章哦!本爬蟲源碼基于WTFPL協(xié)議,感興趣的小伙伴們可以參考一下2016-01-01
nodejs中art-template模板語法的引入及沖突解決方案
本篇文章主要介紹了nodejs中art-template模板語法的引入及沖突解決方案,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-11-11
詳解Wondows下Node.js使用MongoDB的環(huán)境配置
這篇文章主要介紹了詳解Wondows下Node.js使用MongoDB的環(huán)境配置,這里使用到了Mongoose驅(qū)動來讓JavaScript操作MongoDB,需要的朋友可以參考下2016-03-03

