Created
June 4, 2012 06:40
-
-
Save smugen/2866710 to your computer and use it in GitHub Desktop.
Node.js Simple Static Web Server
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
var fs = require('fs'), | |
cluster = require('cluster'); | |
var config = JSON.parse(fs.readFileSync(require('path').join(__dirname, 'config.json'))); | |
if (config.cwd && process.cwd() != config.cwd) process.chdir(config.cwd); | |
var workers = config.workers || require('os').cpus().length; | |
// 如有指定 log 檔,則將標準輸出和錯誤輸出寫到 log 檔 | |
if (config.log){ | |
var log_stream = fs.createWriteStream(config.log, {flags: 'a'}); | |
process.__defineGetter__('stdout', function(){ return log_stream; }); | |
process.__defineGetter__('stderr', function(){ return log_stream; }); | |
} | |
if (cluster.isMaster){ | |
master(); | |
} else { | |
require('./worker.js').run(config); | |
} | |
function master(){ | |
// Fork workers. | |
for (var i = 0; i < workers; i++) cluster.fork(); | |
cluster.on('death', function(worker){ | |
console.log('worker %d died. restart...', worker.pid); | |
cluster.fork(); | |
}); | |
} |
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
{ | |
"cwd": "N:\\Path\\To\\NodeStaticServer\\", | |
"workers": 2, | |
"port": 80, | |
"webroot": "N:\\Path\\To\\Web\\", | |
"log": "server.log" | |
} |
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
(function (){ | |
var connect = require('connect'); | |
// 瀏覽器快取時間 5 分鐘 (maxAge 單位 ms),資料夾網址尾端自動加 "/" | |
var static_options = {maxAge: 1000* 60 * 5, redirect: true}; | |
// http server app | |
var app = connect() | |
.use(connect.logger()) // http://www.senchalabs.org/connect/logger.html | |
.use(connect.compress()) // http://www.senchalabs.org/connect/compress.html | |
.use(connect.staticCache()) // http://www.senchalabs.org/connect/staticCache.html | |
.use(function(req, res, next){ // 預設首頁 | |
if (req.url == '/') req.url += 'index.htm'; | |
res.setHeader('Server', 'Node.js '+process.version); | |
next(); | |
}) | |
// http://www.senchalabs.org/connect/static.html | |
//.use(connect.static(config.webroot, static_options)); | |
//.listen(config.port || 80); | |
exports.run = function(config){ | |
app.use(connect.static(config.webroot, static_options)) | |
.listen(config.port || 80); | |
}; | |
}).call(this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment