SR Office

ブログ
2013年3月11日

Node.jsを使ってみる2

前回の続き

SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.all();

リクエストのルーティング化

ルーターを作成してルーティングできるようにした。匿名クラスはどうしても好きになれない。

Stardust:Node user$ node index.js
Server has started.
Request for /start received.
Request received.
About to route a request for /start
Request for /favicon.ico received.
Request received.
About to route a request for /favicon.ico

ちゃんと動いている。

  • 本当のリクエストハンドラへのルーティング

とりあえずrequesthander.jsファイルにハンドラーを記述してみる。

javascriptは連想配列に関数を設定できるようだ。なのでこんなコードがかける。

var handle = {}
handle[”/”] = requestHandlers.start;

function route(handle) {
if (typeof handle[0] === ‘function’) {
handle0; —> ここのこと!
} else {
console.log(“No request handler);
}
}

これで関数が呼び出せる。コードを修正して起動してみた。

http://localhost:8888/startでアクセス

Stardust:Node user$ node index.js
Server has started.
Request for /start received.
Request received.
About to route a request for /start
Request handler ‘start’ was called.
Request for /favicon.ico received.
Request received.
About to route a request for /favicon.ico
No request handler found for /favicon.ico

今度はhttp://localhost:8888/のみでアクセスしてみる。

Request for / received.
Request received.
About to route a request for /
Request handler ‘start’ was called.
Request for /favicon.ico received.
Request received.
About to route a request for /favicon.ico
No request handler found for /favicon.ico

ちゃんと動いているようだ。

  • リクエストハンドラによる応答

nodeではノンブロッキング処理が基本で、イベント駆動に対応させる必要がある。非同期のCallback関数を設定した場合、responseを終了する場所を考えよう。server.jsのstartメソッド内でroute()メソッド後response.endを呼び出してしまうと、Callback関数が終了する前にレスポンスを返してしまうので、真っ白な画面が表示されるだけになる。注意が必要である。

function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log(“Request for “ + pathname + “ received.”);
console.log(“Request received.”);

route(handle,pathname,response);

response.end(); —> これだ!これがダメだった。
}

http.createServer(onRequest).listen(8888);
console.log(“Server has started.”);
}

  • 有益なものを提供する

この章問題なく、upload処理まで終わった。requestに対してListenerを追加するところなどは、Java,PHPなどのフレームワークと同様なので扱いやすい。あと外部モジュールを使って画像ファイルとPostデータ周りも他のフレームワークと変わりはない。

いまさらながら、Socket通信がなかったような。Nodeは簡単にSocket通信できるがウリだったような次はSocket.IOを試してみよう。