今回の環境

Mac OS X Yosemite 10.10.5

nodebrew で Node.js v5.0.0 をインストールする

事前に nodebrew をインストールしておく。参考 ⇒ [ヅ] Node.js のバージョンを nodebrew で管理する (with Mac OS X + Homebrew) (2015-03-13)


$ nodebrew ls-all | grep 5.0.0
v5.0.0

$ nodebrew install-binary v5.0.0
fetch: http://nodejs.org/dist/v5.0.0/node-v5.0.0-darwin-x64.tar.gz
######################################################################## 100.0%
Install successful

$ nodebrew use v5.0.0
use v5.0.0

$ nodebrew ls | grep current
current: v5.0.0

$ which node
/Users/alice/.nodebrew/current/bin/node

$ node --version
v5.0.0

Web サーバーを実装する


$ cat ./webserver.js

var http = require('http');
var url = require('url');

var escapeHtml = function(str){
  str = str.replace(/&/g, '&');
  str = str.replace(/</g, '&lt;');
  str = str.replace(/>/g, '&gt;');
  str = str.replace(/'/g, '&#39;');
  str = str.replace(/"/g, '&quot;');
  return str;
};

var error = function(req, res){
  res.writeHead(404, {'Content-Type': 'text/html'});
  res.end('<html><body>404 not found</body></html>\n');
};

var server = http.createServer(function(req, res){

  if (req.method !== 'GET') {
    error(req, res);
    return;
  }

  var pathname = url.parse(req.url).pathname;
  var path = '/hello/';

  if(pathname.substr(0, path.length) === path){
    var name = pathname.substr(path.length);
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('<html><body>\n');
    res.write('Hello, ' + escapeHtml(name) + '\n');
    res.write("</body></html>\n");
    res.end();
  }else{
    error(req, res);
  }
});

server.listen(8080);
console.log('my server started');

Web サーバを起動する


$ node ./webserver.js
my server started

Web サーバにアクセスする


$ curl http://localhost:8080/
<html><body>404 not found</body></html>

$ curl http://localhost:8080/hello/Alice
<html><body>
Hello, Alice
</body></html>

$ curl http://localhost:8080/hello/Bob
<html><body>
Hello, Bob
</body></html>

(∩´∀`)∩ うごいた〜

参考資料

tags: node.js javascript

Posted by NI-Lab. (@nilab)