项目在node本地服务器上运行
先看一下项目结构:
1.把项目文件和这两个js文件放在一个文件夹下,我这块把这三个东西放到一个叫“begin”的文件夹下。
2.http.js的内容如下:
var PORT = 3010;//项目在本地运行的端口号
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("customer-fe_sys", pathname); //这里设置自己的项目的文件名称;
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 + ".");
(注意:记得要把项目文件名改变为你的项目名)
3.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"
};
4.选择begin文件夹,同时点击shift+鼠标右键,打开Powershell窗口。
输入node http.js并回车。
5.然后打开网址并输入:
http://127.0.0.1:3010/index.html (注意index.htmlzai你项目下的相对位置)
就可以启动了。