NodeJS搭建本地服務器環境

第一步:創建server.js和mine.js文件

server.js

var http = require('http'),
	url = require('url'),
	fs = require('fs'),
	path = require('path'),
	mine = require('./mine').types,
	PORT = 3000;

var server = http.createServer(function(request, response){
	var pathname = url.parse(request.url).pathname,
		realPath = path.join('bi_pc', pathname),	//注意這裏更改爲項目名稱bi_pc
		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"
}


第二步:項目文件夾(這裏是bi_pc)和這兩個js文件放在同級目錄


第三步:切換到該目錄下,執行node server.js,瀏覽器訪問localhost:3000/index.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章