Nodejs入门
老大让做一个简单的Http服务器响应的东西,可是服务器端的脚本一点点也不会,ruby到现在也没怎么入门,想起nodejs可以做简单快速的服务器端,就用这个了
其实需求很简单就是响应URL的参数请求做一些简单的响应,nodejs用的是javascript,方法也不是很复杂,module也不用太多,觉得挺适合的,于是就从0开始了
下载源码,编译,看sample,就开始写了。
源码如下
var sys = require("util"),
http = require("http"),url = require("url");
var fs = require("fs");
var querystring = require("querystring");
http.createServer(function(request, response) {
console.log("request version" + request.httpVersion + " request headers " + request.headers["Content-Type"] + " " + JSON.stringify(request.headers)) ;
var pathname = url.parse(request.url).pathname;
var search = url.parse(request.url).search;
var query = url.parse(request.url).query;
if(pathname == '/update.zip'){
fs.readFile("./update.zip", "binary", function(error, file) {
if(error) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(error + "\n");
response.end();
} else {
response.writeHead(200, {"Content-Type": "application/zip"});
response.write(file, "binary");
response.end();
}
});
}else{
console.log("pathname = " + pathname+"search "+search + " query = "+ query);
response.writeHeader(200, {"Content-Type": "text/html"});
var param = querystring.parse(query);
var srcversion = param["swv"];
console.log(" param = " + param["hw"]);
// response.writeHeader(200, {"Content-Type": "text/html"});
response.write('<?xml version="1.0" encoding="UTF-8"?>');
response.write('<OTAPackage><srcVersion>'+srcversion +'</srcVersion>');
response.write('<dstVersion>'+'higher version'+'</dstVersion>');
response.write('<description><![CDATA[OTA_030_042]]></description>');
response.write('<downloadURL>http://192.168.0.154:8080/update.zip</downloadURL>');
response.write('<size>7953346</size>');
response.write('<priority>Optional</priority>');
response.write('<sessionId>007d0d21-64c8-4768-9f91-d1ae5268113f</sessionId>');
response.write('</OTAPackage>');
response.end();
}
}).listen(8080,"192.168.0.154");
sys.puts("Server running at http://www.zzzyk.com /");
就是这么简单的东西,刚开始的时候response没有写end,结果只能第一次响应正确,后面的全都挂了,http协议也不是太熟悉,具体原因也没搞清楚,有知道的高手请告知一下,谢谢了
摘自 shcalm的专栏
补充:web前端 , JavaScript ,