nodejs搭建本地http服務(wù)器教程
由于不做php相關(guān)的東西,懶得裝apache,干脆利用nodejs搭建一個本地的服務(wù)器用于測試。
nodejs這玩意兒吧,對做前端的介入后端簡直就是一把利器。而且目前,nodejs也越來越有商用價值。
nodejs其實是非常底層的,從功能上說,它既是apache也是php。像搭建http服務(wù)器這種功能,本來是apache已經(jīng)封裝好的,但nodejs需要我們手動來搭建。其實在實際應(yīng)用中,我們可以使用現(xiàn)成的框架。但這里,我想手動搭建,也加深一下對http服務(wù)器的理解。
我們node執(zhí)行下面這個文件,我命名為http.js,它將創(chuàng)建一個httpServer并監(jiān)聽3000端口。
var PORT = 3000;
var http = require('http');
var url=require('url');
var fs=require('fs');
var mine=require('./mine').types;
var path=require('path');
var server = http.createServer(function (request, response) {
var pathname = url.parse(request.url).pathname;
var realPath = path.join("assets", pathname);
//console.log(realPath);
var ext = path.extname(realPath);
ext = ext ? ext.slice(1) : 'unknown';
fs.exists(realPath, function (exists) {
if (!exists) {
response.writeHead(404, {
'Content-Type': 'text/plain'
});
response.write("This request URL " + pathname + " was not found on this server.");
response.end();
} else {
fs.readFile(realPath, "binary", function (err, file) {
if (err) {
response.writeHead(500, {
'Content-Type': 'text/plain'
});
response.end(err);
} else {
var contentType = mine[ext] || "text/plain";
response.writeHead(200, {
'Content-Type': contentType
});
response.write(file, "binary");
response.end();
}
});
}
});
});
server.listen(PORT);
console.log("Server runing at port: " + PORT + ".");
上面我們還引入了一個mine.js,這是我自己寫的,里面存儲的是名值對,用于定義不同后綴的文件所對應(yīng)的返回方式:
exports.types = {
"css": "text/css",
"gif": "image/gif",
"html": "text/html",
"ico": "image/x-icon",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"js": "text/javascript",
"json": "application/json",
"pdf": "application/pdf",
"png": "image/png",
"svg": "image/svg+xml",
"swf": "application/x-shockwave-flash",
"tiff": "image/tiff",
"txt": "text/plain",
"wav": "audio/x-wav",
"wma": "audio/x-ms-wma",
"wmv": "video/x-ms-wmv",
"xml": "text/xml"
};
fs模塊是用于讀取文件的,提供讀取文件的方法,其實仔細研究文檔會發(fā)現(xiàn),它有同步和異步兩種讀取方式。fs.exists這個方法網(wǎng)上很多文章寫作path.exists,,現(xiàn)在推薦寫作fs.exists這個方法。否則會報警:

需要注意的是,不僅瀏覽器訪問html文件會形成一次訪問,里面鏈接的js,css等外部文件也會分別形成一次http訪問。所以,http.createServer的回調(diào)其實是在一次頁面訪問中執(zhí)行了多次的。我們console.log(realPath)一下就可以看到:

這里并沒有加入默認訪問index.html的功能,所以訪問地址要寫全http://127.0.0.1:3000/index.html
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
NodeJS 將文件夾按照存放路徑變成一個對應(yīng)的JSON的方法
這篇文章主要介紹了NodeJS 將文件夾按照存放路徑變成一個對應(yīng)的JSON的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-10-10
解決node.js含有%百分號時發(fā)送get請求時瀏覽器地址自動編碼的問題
這篇文章主要介紹了解決node.js含有%百分號時發(fā)送get請求時瀏覽器地址自動編碼的問題,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-11-11
解決nodejs報錯Error:EPERM:operation not permitted,mkdi
這篇文章主要介紹了解決nodejs報錯Error:EPERM:operation not permitted,mkdir‘xxxxxxxxxxxxxxxx‘問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02

