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>https://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 /");
就是這麼簡單的東西,剛開始的時候response沒有寫end,結果隻能第一次響應正確,後面的全都掛瞭,http協議也不是太熟悉,具體原因也沒搞清楚,有知道的高手請告知一下,謝謝瞭

摘自 shcalm的專欄

發佈留言