Last active
December 16, 2015 08:08
-
-
Save jun784/5403510 to your computer and use it in GitHub Desktop.
Nodeクックブック
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
npm -g install hotnode # 自動読み込み, or node-dev? | |
httpサーバーをたてるには | |
require('http') | |
pathを解析・デコード | |
require('path') | |
forEachのコールバックは例外で、 | |
実行中はブロックされる。 | |
# forEachはECMAScript5(ES5)の標準実装 | |
fs.stat | |
atime //最終アクセス日時 | |
mtime //最終修正日時 | |
ctime //最終変更日時 | |
fs(filesystem) module | |
var mimeType = { | |
'.js': 'text/javascript', | |
'.html': 'text/html', .... | |
} | |
recipe 1.3 コンテンツキャッシュ | |
cacheAndDeliver (f, cb) -> | |
fs.stat f, (err, stats) -> | |
lastChange = Date.parse(stats.ctime) | |
isUploaded = cache[f] && lastChanged > cache[f].timestamp; | |
if !cache[f] || isUploaded | |
cache[f] = | |
content: data, | |
timestamp: Date.now() // UNIX TIME STAMP | |
fs.readfile f, (err, data) -> | |
if !err | |
cache[f] = {content: data} | |
cb err, data | |
return | |
console.log f + 'をキャッシュから読み込みます。' | |
cb null, cache[f].content | |
1.4 ストリーミングでパフォーマンスを最適化 | |
※responseにpipeすることでデータ全体をロードをせずとも細切れにネットワークソケットに送ることができる | |
s = createReadstream(f, {bufferSize: 128*1024}).once('open', () -> | |
respinse.writeHead 200, headers | |
this.pipe response | |
// cache処理 | |
fs.stat f, (err, stats) -> | |
bufferOffset = 0 | |
cache[f] = {content: new Buffer(stats.size)} | |
s.on 'data', (data) -> | |
data.copy(cache[f].content, bufferOffset) | |
bufferOffset += data.length | |
1.4.1 システムをバッファオーバフローから守る | |
cache = | |
store: {} | |
maxSize: 26214400 // 25MB 最大ファイルサイズを決める | |
maxAge : 5400 * 1000 // 1.5時間 最大保存期間を決める | |
cleanAfter: 7200 * 1000 // 2時間 | |
cleanedAt: 0 | |
if now - this.cleanAfter > this.cleanedAt | |
this.cleanAt = now | |
that = this | |
Object.key(this.store).forEach (file) -> | |
if now > that.store[file].timestamp + that.MaxAge | |
delete that.store[file] | |
1.5.2 node-static | |
# キャッシュ制御, streamを使ったコンテンツ配信, 相対パスやNULLフィルタパス |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment