作为前端的我们,在服务端部署一个应用,也是我们应该掌握的一项技术,目前比较流行的服务器有apache,IIs等,关于这两个服务器的部署,这里就不介绍了,今天想介绍的是nodejs部署我们的一个应用。
首先,这个方法是windows电脑上的,也是新学习,做一下记录。
拥有windows电脑之后,你还必须在windows电脑上安装node环境,安装链接(http://jingyan.baidu.com/article/a948d6515d4c850a2dcd2e18.html)
在一个文件夹中新建一个js文件,如action.js,内容如下:
var PORT = 8083;//
var appPath = "D:/code/demo/clienth5/code/H5Demo/assets/apps/payassistant";
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(appPath, pathname); //这里设置自己的文件名称;
console.log("pathname:" + pathname + ";realPath:" + 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/html";
response.writeHead(200, {
'Content-Type': contentType
});
response.write(file, "binary");
response.end();
}
});
}
});
});
server.listen(PORT);
console.log("Server runing at port: " + PORT + ".");
当然,我们一般情况下一个主页面会应用很多图片,css,js等,所以我们还需要导入模块,新建一个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"
};
也就是var mine=require('./mine').types;这个用处。
完成上面的代码
执行 $node action.js
将会打印:
Server runing at port: 8083
说明:
其中appPath是你应用的绝对路径,比如我的payassistant文件夹下有个main.html,然后直接在浏览器访问:
loacalhost:8083/main.html即可。