nodejs 如何手動(dòng)實(shí)現(xiàn)服務(wù)器
這是一個(gè)連續(xù)的node學(xué)習(xí)筆記, 本文是第一章, 會(huì)持續(xù)更新, 持續(xù)完善
python好用,用久了就會(huì)把人的脾氣養(yǎng)起來(lái), nodejs不好用, 但效率很好, 也能徹底治好你的壞脾氣
nodejs的回調(diào)是我用過(guò)的最蛋疼的編程方式之一, 但也足夠巧妙, 學(xué)好node, 對(duì)一個(gè)程序員而言, 也是一個(gè)穩(wěn)賺不賠的買(mǎi)賣(mài)
廢話(huà)不多說(shuō), 上代碼
1. 完成環(huán)境的搭建, 運(yùn)行一個(gè)正則,提取字符串中的數(shù)字
let numRe = /\d+/g;
console.log("123dsgfas 12434 sdfasdf234dagsdfg".match(numRe));
nodejs的語(yǔ)法和瀏覽器js的語(yǔ)法非常接近, 安裝好node后, 可以寫(xiě)個(gè)正則, 測(cè)試一下環(huán)境是否安裝成功, 通過(guò)atom的script插件容易造成端口占用,建議學(xué)習(xí)過(guò)程中用命令行工具執(zhí)行node腳本, 如 node HelloWorld.js
2. http模塊開(kāi)啟一個(gè)服務(wù)
const http = require("http")
//開(kāi)啟一個(gè)監(jiān)聽(tīng)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)
開(kāi)啟服務(wù),分三步:
第一步: 引入模塊
第二步: 調(diào)用模塊http.createServer
第三步: 監(jiān)聽(tīng)端口http.createServer(function(req, res){}).listen(8080)
3. fs模塊讀寫(xiě)文件
const fs = require("fs");
// 寫(xiě)入文件
fs.writeFile("HelloWorld.txt", "HelloWorld HelloNode", function(err){
if(err){
console.log(err);
}
// 讀取剛剛寫(xiě)入的數(shù)據(jù)
else{
fs.readFile("HelloWorld.txt", function(err, data) {
if(err){
console.log(err);
}else{
console.log(data.toString());
}
})
}
})
簡(jiǎn)單讀寫(xiě)文件非常簡(jiǎn)單, 與其它編程語(yǔ)言類(lèi)似, 把調(diào)用方法背過(guò)就可以了
4.實(shí)現(xiàn)一個(gè)靜態(tài)http服務(wù)器
const http = require("http");
const fs = require("fs")
http.createServer(function(req, res){
// 打開(kāi) 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)
通過(guò)了讀取 www/ 目錄下的文件, 實(shí)現(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請(qǐng)求的參數(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請(qǐng)求的參數(shù)
小結(jié): 用已有知識(shí) 實(shí)現(xiàn)簡(jiǎn)單的服務(wù)器程序
const http = require("http");
const fs = require("fs");
const querystring = require("querystring");
/*
*1. 訪(fǎng)問(wèn)www內(nèi)的靜態(tài)資源
*2. 解析get請(qǐng)求, 并保存到serverLog.txt
*3. 解析post請(qǐng)求serverLog.txt
*/
// 獲取當(dāng)前時(shí)間
function getNowDate(){
let dt = new Date();
let year = dt.getFullYear();
let month = dt.getMonth();
let day = dt.getDate();
// 將月份加1
month = month + 1;
// 將月份補(bǔ)齊到兩位
if (month <= 9){
month = "0" + month;
}
// 將日補(bǔ)齊到兩位
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. 嘗試訪(fǎng)問(wèn)www下的靜態(tài)資源
fs.readFile("./www"+req.url, function(err, data){
if(err){
//2. 解析請(qǐng)求的參數(shù), 并保存到log
if(req.method === "GET"){
console.log("收到了GET請(qǐng)求")
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出錯(cuò)");
}
});
}else if (req.method == "POST") {
console.log("收到了POST請(qǐng)求")
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出錯(cuò)");
}
});
})
}
res.write("404");
res.end();
}else{
res.write(data);
res.end();
}
})
}).listen(8000)
python測(cè)試腳本
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)機(jī)制, 用原生nodejs寫(xiě)服務(wù)器程序是一件很有效率的事情 , 測(cè)試腳本還是requests好用!
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- nodejs express配置自簽名https服務(wù)器的方法
- 通過(guò)nodejs 服務(wù)器讀取HTML文件渲染到頁(yè)面的方法
- 利用nodeJs anywhere搭建本地服務(wù)器環(huán)境的方法
- NodeJs搭建本地服務(wù)器之使用手機(jī)訪(fǎng)問(wèn)的實(shí)例講解
- nodeJS服務(wù)器的創(chuàng)建和重新啟動(dòng)的實(shí)現(xiàn)方法
- nodejs搭建本地服務(wù)器輕松解決跨域問(wèn)題
- nodejs實(shí)現(xiàn)的簡(jiǎn)單web服務(wù)器功能示例
- nodejs簡(jiǎn)單實(shí)現(xiàn)TCP服務(wù)器端和客戶(hù)端的聊天功能示例
- nodejs創(chuàng)建簡(jiǎn)易web服務(wù)器與文件讀寫(xiě)的實(shí)例
相關(guān)文章
Nodejs中使用puppeteer控制瀏覽器中視頻播放功能
本項(xiàng)目主要功能為在瀏覽器中自動(dòng)播放視頻,并且實(shí)現(xiàn)音量控制,快進(jìn)快退,全屏控制,播放暫停控制等功能。對(duì)Nodejs中使用puppeteer控制瀏覽器中視頻播放功能感興趣的朋友跟隨小編一起看看吧2019-08-08
基于Node.js的強(qiáng)大爬蟲(chóng) 能直接發(fā)布抓取的文章哦
基于Node.js的強(qiáng)大爬蟲(chóng)能直接發(fā)布抓取的文章哦!本爬蟲(chóng)源碼基于WTFPL協(xié)議,感興趣的小伙伴們可以參考一下2016-01-01
Linux?Ubuntu升級(jí)nodejs版本的簡(jiǎn)單步驟
Node.js是一種對(duì)應(yīng)于JavaScript運(yùn)行時(shí)環(huán)境的編程語(yǔ)言,這篇文章主要給大家介紹了關(guān)于Linux?Ubuntu升級(jí)nodejs版本的簡(jiǎn)單步驟,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-12-12
nodejs中art-template模板語(yǔ)法的引入及沖突解決方案
本篇文章主要介紹了nodejs中art-template模板語(yǔ)法的引入及沖突解決方案,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-11-11
Node.js實(shí)現(xiàn)登錄注冊(cè)功能
這篇文章主要為大家詳細(xì)介紹了Node.js實(shí)現(xiàn)登錄注冊(cè)功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04
Node.js編寫(xiě)組件的三種實(shí)現(xiàn)方式
這篇文章主要介紹了Node.js編寫(xiě)組件的三種實(shí)現(xiàn)方式,包括純js實(shí)現(xiàn)、v8 API實(shí)現(xiàn)(同步&異步)、借助swig框架實(shí)現(xiàn),感興趣的小伙伴們可以參考一下2016-02-02
詳解Wondows下Node.js使用MongoDB的環(huán)境配置
這篇文章主要介紹了詳解Wondows下Node.js使用MongoDB的環(huán)境配置,這里使用到了Mongoose驅(qū)動(dòng)來(lái)讓JavaScript操作MongoDB,需要的朋友可以參考下2016-03-03
關(guān)于npm?i幾種常見(jiàn)命令的區(qū)別詳解
npm(Node.js Package Manager)是一個(gè)Node.js的包管理工具,用來(lái)解決Node.js代碼部署問(wèn)題,下面這篇文章主要給大家介紹了關(guān)于npm?i幾種常見(jiàn)命令的那點(diǎn)事,需要的朋友可以參考下2023-03-03

