node.js練習その1

var http = require('http'),
    fs = require('fs'),
    util = require('util'),

    host = '127.0.0.1',
    port = 1337;

http.createServer(function (req, res) {

  fs.readFile('./index.html', function (err, data) {

    if (err) {
      throw err;
    }

    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(data);

  });

}).listen(port, host);

console.log(
    util.format('Server running at http://%s:%s/', host, port));

ファイルを返すのはこんな感じでいいのかな?
でもこれだと成功するのが前提だな……


追記:

var http = require('http'),
    fs = require('fs'),
    util = require('util'),

    host = '127.0.0.1',
    port = 1337;

process.on('uncaughtException', function (err) {
  console.error('uncaughtException: ' + err);
});

http.createServer(function (req, res) {
  
  var file = './index.html';
  
  fs.stat(file, function (err, stats) {
    
    if (err) {
      res.writeHead(404, {'Content-Type': 'text/plain'});
      res.end('404 Not Found? : ' + err);
      
      return;
    }

    if (stats.isFile()) {
      fs.readFile(file, function (err, data) {

        if (err) {
          throw err;
        }

        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end(data);

      });
      
      return;
    }
    
  });
  
}).listen(port, host);

console.log(
    util.format('Server running at http://%s:%s/', host, port));

こんな感じ?