ファイル操作する場合は、fsモジュールを読み込む必要があります。
このモジュールの
readFileメソッドを使用してファイルを読み込んでそのままブラウザに表示してみます。
var http = require('http'),
fs = require('fs');
http.createServer(function(req, res) {
fs.readFile('index.html', 'UTF-8',function(err, content) {
if (err) {
throw err;
}
res.writeHead(200, {'Content-Type':'text/html'});
res.end(content);
});
}).listen(8084, '127.0.0.1');
readFileメソッドのコールバック関数の第2引数が、ファイル内容になります。
なので、res.endメソッドの引数にcontentをそのまま入れています。上記のソースをserver.jsとして保存します。
次にindex.htmlとして以下のソースを保存します。
<!doctype HTML>
<html>
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
Hello World
</body>
</html>
サーバ起動するとブラウザは以下のように表示されます。
ブラウザ画面