nodejs轻量服务器后端
生活随笔
收集整理的這篇文章主要介紹了
nodejs轻量服务器后端
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
nodejs輕量服務(wù)器后端
搭建思路
server.js主函數(shù) + mine.js配置文件 + index.html 測試網(wǎng)頁
目錄結(jié)構(gòu)
__./|__ test1|__ index.html|__ mine.js|__ server.jsserver.js文件
var PORT = 8080; //端口 var DIR = 'test1'; //用于存放html的目錄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(DIR, 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
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" };測試網(wǎng)頁自備index.html
<h1>hello world</h1>執(zhí)行腳本
node server.js總結(jié)
以上是生活随笔為你收集整理的nodejs轻量服务器后端的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 初识C++之虚函数
- 下一篇: linux云服务器状态上报解决方案:外发