您的位置:首页 > Web前端 > Node.js

NodeJS搭建本地服务器环境

2016-11-18 11:17 417 查看
第一步:创建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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: