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 です。
> npm init
package.json ファイルの内容は、以下のようになります。
package.json
{
"name": "express_test",
"version": "1.0.0",
"description": "express test.",
"main": "index.js",
"scripts": {
"test": "test"
},
"author": "",
"license": "ISC",
}
expressの インストール
以下のコマンドを入力して、express をインストールします。
> npm install --save express
package.json に、express が追加されます。
package.json
{
"name": "express_test",
"version": "1.0.0",
"description": "express test.",
"main": "index.js",
"scripts": {
"test": "test"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.14.1"
}
}
Hello World の表示
作業ディレクトリに app.js というファイルを作成し、以下の内容を書き込みます。
app.js
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
端末に以下のコマンドを入力し、アプリケーションを実行します。
> node app.js
ブラウザを開き http://localhost:3000/
にアクセスして Hello World! と表示されれば成功です。
express generator を利用する
アプリケーションのスケルトンを生成するためのツールである express generator を利用して、アプリケーションの雛形を作成します。
express generator のインストール
以下のコマンドを入力して、express generator をインストールします。
> npm install --g express-generator
スケルトンの作成
作業フォルダに移動して、以下のコマンドを実行し、アプリケーションのスケルトンを作成します。
> express myapp
create : myapp
create : myapp/package.json
create : myapp/app.js
create : myapp/public/javascripts
create : myapp/routes
create : myapp/routes/index.js
create : myapp/routes/users.js
create : myapp/views
create : myapp/views/index.jade
create : myapp/views/layout.jade
create : myapp/views/error.jade
create : myapp/public
create : myapp/public/images
create : myapp/public/stylesheets
create : myapp/public/stylesheets/style.css
create : myapp/bin
create : myapp/bin/www
以下のようなアプリケーションのスケルトンが作成されます。
myapp
┣ bin
┃ ┗ www
┣ public
┃ ┣ images
┃ ┣ javascripts
┃ ┗ stylesheets
┃ ┗ style.css
┣ routes
┃ ┣ index.js
┃ ┗ users.js
┣ views
┃ ┣ error.jade
┃ ┣ index.jade
┃ ┗ layout.jade
┣ app.js
┗ package.json
依存関係のモジュールのインストール
作成されたアプリケーションのフォルダに移動し、以下のコマンドを入力して、モジュールをインストールします。
myapp> npm install
実行
端末に以下のコマンドを入力し、アプリケーションを実行します。
myapp> npm start
ブラウザを開き http://localhost:3000/
にアクセスして、Express の画面が表示されれば成功です。