2011-06-08 25 views
0

在此代碼中:如果我嘗試將this.handler作爲參數傳遞給server.createServer(),那麼我得不到任何響應(頁面一直在瀏覽器中加載)。但如果我使用server.createServer(函數(REQ,RES){/ /相同的代碼在這裏處理程序()}),然後它的作品。我究竟做錯了什麼?作爲node.js模塊中的參數

var Con = module.exports = function() { 
    process.EventEmitter.call(this); 
} 

var createServer = module.exports.createServer = function(options) { 
    console.log('start'); 
    this.port = options.port || 9122; 
    this.secure = options.secure || false; 
    if(this.secure === true) 
     if(!options.key || !options.certificate) 
      this.secure = false; 
     else { 
      this.key = options.key; 
      this.certificate = options.certificate; 
     } 

    if(this.secure) { 
     this.server = require('https'); 
     var fs = require('fs'); 
     var opt = { 
      key: fs.readFileSync('privatekey.pem'), 
      cert: fs.readFileSync('certificate.pem') 
     }; 
     this.server.createServer(opt, this.handler).listen(this.port); 
    } else { 
     this.server = require('http'); 
     this.server.createServer(this.handler).listen(this.port); 
    } 
} 

Con.prototype.handler = function(req, res) { 
    console.log('request'); 
    res.writeHead(200); 
    res.write(req.url); 
    res.end(); 
} 

回答

1
var Con = function() { 
    process.EventEmitter.call(this); 
} 

這就是你的constuctor

module.exports = new Con(); 

這是您的實例

var createServer = module.exports.createServer = function(options) { 
    console.log('start'); 
    this.port = options.port || 9122; 
    this.secure = options.secure || false; 
    if(this.secure === true) 
     if(!options.key || !options.certificate) 
      this.secure = false; 
     else { 
      this.key = options.key; 
      this.certificate = options.certificate; 
     } 

    if(this.secure) { 
     this.server = require('https'); 
     var fs = require('fs'); 
     var opt = { 
      key: fs.readFileSync('privatekey.pem'), 
      cert: fs.readFileSync('certificate.pem') 
     }; 
     this.server.createServer(opt, this.handler).listen(this.port); 
    } else { 
     this.server = require('http'); 
     this.server.createServer(this.handler).listen(this.port); 
    } 
} 

.createServer現在在實例的方法甚則構造

因爲它是在實例也訪問過原型的實例定義的.handler方法。

+0

謝謝,它的工作原理 – 2011-06-08 14:16:54