developers blog

Node.js のフレームワーク Express を動かす

はじめに

node.js のフレームワークの1つ Express を動かします。

環境

  • OS : Windows 7 Pro 64bit
  • その他 : node.js v6.9.4, npm 3.10.10

express で Hello World

express 公式にある Hello World の例を動かします。

package.json の作成

作業フォルダに移動し、以下のコマンドを入力して package.json を作成します。内容は適当で OK です。

1> npm init

package.json ファイルの内容は、以下のようになります。

package.json
1{
2  "name": "express_test",
3  "version": "1.0.0",
4  "description": "express test.",
5  "main": "index.js",
6  "scripts": {
7    "test": "test"
8  },
9  "author": "",
10  "license": "ISC",
11}

expressの インストール

以下のコマンドを入力して、express をインストールします。

1> npm install --save express

package.json に、express が追加されます。

package.json
1  {
2    "name": "express_test",
3    "version": "1.0.0",
4    "description": "express test.",
5    "main": "index.js",
6    "scripts": {
7      "test": "test"
8    },
9    "author": "",
10    "license": "ISC",
11    "dependencies": {
12      "express": "^4.14.1"
13    }
14}

Hello World の表示

作業ディレクトリに app.js というファイルを作成し、以下の内容を書き込みます。

app.js
1var express = require('express');
2var app = express();
3
4app.get('/', function (req, res) {
5  res.send('Hello World!');
6});
7
8app.listen(3000, function () {
9  console.log('Example app listening on port 3000!');
10});

端末に以下のコマンドを入力し、アプリケーションを実行します。

1> node app.js

ブラウザを開き http://localhost:3000/ にアクセスして Hello World! と表示されれば成功です。

express generator を利用する

アプリケーションのスケルトンを生成するためのツールである express generator を利用して、アプリケーションの雛形を作成します。

express generator のインストール

以下のコマンドを入力して、express generator をインストールします。

1> npm install --g express-generator

スケルトンの作成

作業フォルダに移動して、以下のコマンドを実行し、アプリケーションのスケルトンを作成します。

1> express myapp
2
3   create : myapp
4   create : myapp/package.json
5   create : myapp/app.js
6   create : myapp/public/javascripts
7   create : myapp/routes
8   create : myapp/routes/index.js
9   create : myapp/routes/users.js
10   create : myapp/views
11   create : myapp/views/index.jade
12   create : myapp/views/layout.jade
13   create : myapp/views/error.jade
14   create : myapp/public
15   create : myapp/public/images
16   create : myapp/public/stylesheets
17   create : myapp/public/stylesheets/style.css
18   create : myapp/bin
19   create : myapp/bin/www

以下のようなアプリケーションのスケルトンが作成されます。

1myapp
2  ┣ bin
3  ┃   ┗ www
4  ┣ public
5  ┃   ┣ images
6  ┃   ┣ javascripts
7  ┃   ┗ stylesheets
8  ┃        ┗ style.css
9  ┣ routes
10  ┃   ┣ index.js
11  ┃   ┗ users.js
12  ┣ views
13  ┃   ┣ error.jade
14  ┃   ┣ index.jade
15  ┃   ┗ layout.jade
16  ┣ app.js
17  ┗ package.json

依存関係のモジュールのインストール

作成されたアプリケーションのフォルダに移動し、以下のコマンドを入力して、モジュールをインストールします。

1myapp> npm install

実行

端末に以下のコマンドを入力し、アプリケーションを実行します。

1myapp> npm start

ブラウザを開き http://localhost:3000/ にアクセスして、Express の画面が表示されれば成功です。