-------------------------前进前进前进进-----------------------------------
1.安装Nodemon,修改所见即所得,无需重启Node服务器
*.npm install -g nodemon
2.在Github上下载一个Node应用:https://github.com/shapeshed/express_example
3.解决中文乱码的问题
将下载包里后缀名为jade的文件另存为Utf8,这样修改内容为中文,也不会有中文乱码的问题
4.寻找云部署站点[免费]:
Heroku:https://devcenter.heroku.com/articles/quickstart
5.以下是我部署成功的NodeJs站点
采用Heroku部署成功:
URL:http://nodejsapp.herokuapp.com/
Git:[email protected]:nodejsapp.git
-------------------------创建静态服务器-----------------------------------
第一种方案:自己创建一个server.js
1.npm以下包:
*.npm install http
*.npm install url
*.npm install path
*.npm install fs
2.创建server.js文件,代码清单如下:
************************************代码开始*******************************************
var http = require("http");
var url = require("url");
var path = require("path");
var fs = require("fs");
//发布端口
var port=1234;
//发布路径
var publish_path="D:\\dev\\nodejs\\content";
//允许访问的MIME类型
var mime = {
"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"
};
/**
* URL 路由
*/
function route(request, response){
var pathname = url.parse(request.url).pathname;
var realPath = publish_path+pathname;
path.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 ext = path.extname(realPath);
ext = ext ? ext.slice(1) : 'unknown';
var contentType = mime[ext] || "text/plain";
response.writeHead(200, {'Content-Type': contentType});
response.write(file, "binary");
response.end();
}
});
}
});
}
/**
* 运行服务器
*/
function server_run(){
function onRequest(request, response) {
route(request, response);
}
http.createServer(onRequest).listen(port);
console.log("Server is running on port "+port+".");
}
server_run();
************************************代码结束*******************************************
3.运行server.js
node server.js
第二种方案:使用Express框架,定义server.js
TODO
参考文献:
Web Framework: Express:https://github.com/visionmedia/express
Express参考手册:http://expressjs.com/guide.html
Creating a Basic Site With node.js and Express:
http://shapeshed.com/creating-a-basic-site-with-node-and-express/
用NodeJS打造你的静态文件服务器:
http://cnodejs.org/topic/4f16442ccae1f4aa27001071