概要

  • サーバーサイドJavaScript
  • 用途:大量のリクエストを高速にさばくメッセージングやAPIなど
  • 公式サイト:https://nodejs.org/

前提知識

  • HTML/JavaScript
  • MongoDB
  • Unixコマンド

環境

  • OS X 10.11 El Capitan
  • Vagrant 1.8.1
  • VirtualBox 5.0.20
  • CentOS 7.2.1511
  • Node.js 0.10.24
  • MongoDB 3.2.6

Node.jsのインストール(yum)

$ sudo yum install nodejs
$ node -v
v0.10.42

MongoDBのインストール(yum)

  • /etc/yum.repos.d/配下にMongoDBリポジトリファイルを作成
# vi mongodb-org-3.2.repo
[mongodb-org-2.6]
name=MongoDB 2.6 Repository
baseurl=http://downloads-distro.mongodb.org/repo/redhat/os/x86_64/
gpgcheck=0
enabled=1
$ sudo yum install -y mongodb-org
$ mongo --version
MongoDB shell version: 3.2.6

スレッドモデルとイベントループ

  • スレッドモデル:Apacheなど
    • 1つのリクエストに対して1つのスレッド
    • 大量のリクエストが来るとメモリが枯渇してスレッドが作成できないためリクエストの待ち状態が発生
  • イベントループモデル:Node.js
    • 全てのリクエストは一度キューに溜まり随時バックエンドで処理
    • 処理の順番は保証しない
    • ノンブロッキングなコードの記述をする必要あり
    • setTimeout等のタイマー処理を含む処理は次の処理をブロックしないようにコールバック関数として実装

Hello World

  • 対話モード
$ node
> console.log("hello world");
hello world
undefined
  • コマンド一覧表示
$ .help
  • hello.js作成
console.log("hello world");
  • 実行
$ node hello.js
hello world

ノンブロッキング処理とブロッキング処理

// non blocking
setTimeout (function () {
	console.log("hello");
}, 1000);
console.log("world");
$ node hello.js
world
hello
// blocking
var start = new Date().getTime();
console.log("hello");
while (new Date().getTime() < start + 1000);
console.log("world");
$ node hello.js
hello
world

Webサーバーを作成

  • server.js作成
var http = require('http');
var server = http.createServer();
server.on('request', function(req, res) {
	res.writeHead(200, {'Content-TYpe': 'text/plain'});
	res.write('hello world');
	res.end();
});
server.listen(1337, '192.168.33.10');
console.log('server listening ...');
$ node server.js
server listening ...

トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2016-05-21 (土) 22:07:09 (2894d)