数学やプログラミングや映画など

新米SEがwebと数学と映画についてつらつら書きたいブログです。

初心者がnodejsでHTMLファイルを処理する話

はじめに

  • この記事はnode.jsでHTTPリクエストに対し、HTMLファイルを返す処理についてまとめる記事です
  • 前の記事ではターミナル上でnode.jsを用いたHello!world!を行いました
  • 前の記事↓

math-it.hatenablog.com

ディレクトリ構造

  • 以下の用なファイルを作成します
[@guestos nodejs]$ tree ./
./
├── html
│   ├── hellonode.html
│   └── notfound.html
└── index.js
1 directory, 3 files

正常なパスのリクエストが来た場合の静的ファイルを作成

  • 正しく存在する場合のHTMLファイルを作成します
  • html/hellonode.html
[@guestos nodejs]$ cat html/hellonode.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Hello!node.js!</title>
</head>
<body>
<h1>Node.jsですよ!</h1>
</body>
</html>

それ以外のパスが指定されたリクエストが来た場合の静的ファイルを作成

  • 存在しないファイルが指定された場合のHTMLファイルを作成します
  • html/notfound.html
[nknsh@guestos nodejs]$ cat html/notfound.html
<!DOCCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>404 notfound!!</title>
</head>
<body>
<h1>ページが見つかりませんでした。</h1>
</body>
</html>

HTTPリクエストを処理するjsファイルを作成

  • 指定されたパスに対し処理を分岐
    • 指定されたパスが存在すれば対応するHTMLファイルを返す
    • そうでなければnotfound用ファイルを返す
    • notfound用ファイルすら存在しなかった場合にnotfound用テキストを返す
  • fsオブジェクトを生成することでHTMLファイルが呼び出せる
    • __dirnameはindex.jsが位置する絶対パスに対応する
    • readFileメソッドの引数
      • 第一引数は読み込むファイルのパス
      • 第二引数は文字コード
      • 第三引数はコールバック関数( エラー, 読み込んだファイル )
[@guestos nodejs]$ cat index.js
var http = require('http');
var server = http.createServer();

var filesystem = require('fs');

server.on('request', function(req, res){
        filesystem.readFile(__dirname + req.url, 'utf-8', function(error, data){
                if(error){
                        filesystem.readFile(__dirname + '/html/notfound.html', 'utf-8', function(notfoundError, notfoundData){
                                if(notfoundError){
                                        res.writeHead(404, {'Content-Type': 'text/plain'});
                                        res.write('notfound!!');
                                        return res.end();
                                }else{
                                        res.writeHead(404, {'Content-Type': 'text/html'});
                                        res.write(notfoundData);
                                        return res.end();
                                }
                        });
                }else{
                        res.writeHead(200, {'Contetnt-Type': 'text/html'});
                        res.write(data);
                        return res.end();
                }
        });
});

server.listen( 3000, '192.168.100.200');
console.log('server listening, port 3000');

実行結果

  • index.jsの実行
[@guestos nodejs]$ node index.js
server listening, port 3000
  • 存在するパスを指定した場合

f:id:nknshmsk:20160801233328p:plain

  • 存在しないパスを指定した場合

f:id:nknshmsk:20160801233242p:plain

まとめ

  • node.jsで静的なHTMLファイルを返すことをしました
  • これでnode.jsを用いたウェブサイト作成の第一歩と言えるかなと思います
  • おすすめの参考書
    • 筆者はこの本を使って勉強しています
    • 割と丁寧だと思うのでお勧めです