Node.jsで簡単なWebサーバを書いてみる

Node.js のインストール

https://nodejs.org/ からインストール

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

サーバ処理の作成

server.js

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);

起動

node server.js

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

サーバ処理の作成

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

server.js

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);  // ポート競合の場合は値を変更

起動

node server.js

トップ   差分 バックアップ リロード   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2016-08-04 (木) 21:41:03 (2820d)