今回の環境: Mac OS X Yosemite 10.10.2


$ uname -mrsv
Darwin 14.1.0 Darwin Kernel Version 14.1.0: Thu Feb 26 19:26:47 PST 2015; root:xnu-2782.10.73~1/RELEASE_X86_64 x86_64

Node.js はインストール済みの状態。


$ node --version
v0.10.29

作業用のディレクトリをつくる。


$ mkdir helloworld
$ cd helloworld/

Node.js のパッケージマネージャ npm で Express モジュールをインストールする。


$ npm install express
express@4.12.2 node_modules/express
├── merge-descriptors@1.0.0
├── utils-merge@1.0.0
├── cookie-signature@1.0.6
├── methods@1.1.1
├── fresh@0.2.4
├── cookie@0.1.2
├── escape-html@1.0.1
├── range-parser@1.0.2
├── content-type@1.0.1
├── vary@1.0.0
├── parseurl@1.3.0
├── finalhandler@0.3.3
├── content-disposition@0.5.0
├── path-to-regexp@0.1.3
├── depd@1.0.0
├── qs@2.3.3
├── etag@1.5.1 (crc@3.2.1)
├── send@0.12.1 (destroy@1.0.3, ms@0.7.0, mime@1.3.4)
├── accepts@1.2.5 (negotiator@0.5.1, mime-types@2.0.10)
├── debug@2.1.3 (ms@0.7.0)
├── on-finished@2.2.0 (ee-first@1.1.0)
├── serve-static@1.9.2 (send@0.12.2)
├── type-is@1.6.1 (media-typer@0.3.0, mime-types@2.0.10)
└── proxy-addr@1.0.6 (forwarded@0.1.0, ipaddr.js@0.1.8)

hello, world 的なサンプルプログラムを用意。


$ cat ./app.js 

var express = require('express');
var app = express();

app.get('/', function(req, res){
  res.send('Hello World!\n');
});

app.get('/echo/', function(req, res){
  res.send('Set your parameter.\n');
});

app.get('/echo/:hoge', function(req, res){
  var hoge = req.params.hoge;
  res.send(hoge + '\n');
});

var server = app.listen(8080, function(){
  var host = server.address().address;
  var port = server.address().port;
  console.log('Example app listening at http://%s:%s', host, port);
});

Node.js を実行して、 Express による Web サーバを起動する。


$ node ./app.js 
Example app listening at http://0.0.0.0:8080

別のターミナルから curl コマンドでアクセスしてみる。


$ curl http://localhost:8080/
Hello World!

$ curl http://localhost:8080/echo
Set your parameter.

$ curl http://localhost:8080/echo/
Set your parameter.

$ curl http://localhost:8080/echo/helloworld
helloworld

$ curl http://localhost:8080/echo/foobar
foobar

$ curl http://localhost:8080/aaaa
Cannot GET /aaaa

ちゃんと動いた(*´∀`*)

tags: node.js express

Posted by NI-Lab. (@nilab)