LoginSignup
2
2

More than 5 years have passed since last update.

[初心者向け] [Node.js] fsモジュールを使ってhtmlファイルを返す

Posted at

Node.jsとは?

以下の記事でNode.jsについてとHello Worldする方法をまとめたため参考にしてください。

htmlファイルを返す

(コードの解説は下にあります。)

hello.jsでhttpサーバーを作成し、htmlを返すします

hello.js
var http = require('http');
var fs = require('fs'); // ①

var server = http.createServer(function(req, res) {
  fs.readFile('./temp.html', 'utf-8', function(err, data) { // ②
    res.writeHead(200, {'Content-Type': 'text/html'}); // ③
    res.write(data);
    res.end();
  })
});

server.listen(3000);
console.log('サーバーを起動しました。');

hello.jsで返されるhtmlファイル

temp.html
<!DOCTYPE html>
<html lang="ja" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>sample</title>
  </head>
  <body>
    <h1>Hello world</h1>
    <p>This is Template file</p>
  </body>
</html>

実行する

$ node hello.js

http://localhost:3000/
にアクセスして、以下の画像の様に表示されれば成功

スクリーンショット 2018-10-06 15.28.00.png

解説

①require関数でfsオブジェクトを生成する

fsオブジェクトはファイルを読み込むためのオブジェクト
https://nodejs.org/api/fs.html

②fsオブジェクトのreadFileメソッドでhtmlファイルを読み込む

  • 第一引数:対象のファイルパス
  • 第二引数:エンコード
  • 第三引数:読み込み完了時に動作するコールバック関数 (コールバック関数では、第一引数にエラーオブジェクト、第二引数に読み込んだデータを受け取る)

③htmlファイル読み込み後にhttpヘッダや読み込み結果を出力させる

readFileメソッドは非同期であるため、コールバック関数で、これらを行わないと、ファイル読み込みが完了する前にレスポンスを返却してしまう。

Content-Typeを「text/html」に変更している

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2