* Node.jsで簡単なWebサーバを書いてみる [#vc7ca6b3]
#setlinebreak(on)

#contents
-- 関連
--- [[Node.js]]
--- [[nodejsでwebsocket]]

** Node.js のインストール [#h6140edc]
https://nodejs.org/ からインストール

** 必ず index.html の内容を返却するWebサーバを書いてみる [#s6d0d302]

#html(<div style="padding:10px;">)

*** サーバ処理の作成 [#na33c29a]
server.js
#mycode2(){{
var fs = require("fs");
var server = require("http").createServer(function(req, res) {
     res.writeHead(200, {"Content-Type":"text/html"});
     var output = fs.readFileSync("./index.html", "utf-8");
     res.end(output);
}).listen(8080);
}}

*** 起動 [#d53ce1e8]
#myterm2(){{
node server.js
}}

#html(</div>)

** リクエストURIに応じてWebルート配下にあるファイルの内容を返すサーバを書いてみる [#n95f2e4d]

#html(<div style="padding:10px;">)

*** サーバ処理の作成 [#f55a6fdb]

とりあえず html, css, js を返却するサーバを書いてみる

server.js
#mycode2(){{
var http = require('http');
var fs = require('fs');
var server = http.createServer(function(req, res) {

    var contentType = "text/html";
    var content = ""; 
    var status = 200;
    var uri = req.url

    var last = uri.substring(uri.length - 1, 1); 
    if (last == "/") {
      uri = uri + "index.html"
    }   

    // TODO: ../ などを指定された時に上位のディレクトリのファイルが読まれてしまわないようにしておくべき。
    var uriary = uri.split(".");
    if (uriary.length >= 2) {
      try {
        kind = uriary[uriary.length - 1]; 
        if (kind == "html" || kind == "htm") {
          contentType = "text/html";
        } else if (kind == "css") {
          contentType = "text/css";
        } else if (kind == "js") {
          contentType = "text/html";
        }   

        content = fs.readFileSync(__dirname + uri);
      } catch (e) {
        status = 404;
        content = "content not found!";
      }   
    } else {
    }   
    res.writeHead(status, {'Content-Type' : contentType});
    res.end(content, 'utf-8');
}).listen(8080);  // ポート競合の場合は値を変更
}}

*** 起動 [#xe042f10]
#myterm2(){{
node server.js
}}

#html(</div>)

トップ   差分 バックアップ リロード   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS