2011-04-22 79 views

回答

1

在server.js,頂部包括account.js>

var account = require("./account");

在你的NodeJS功能createServer,你檢查URI是/帳號>

//Create Server 
http.createServer(function (request, response) { 
    // Parse the entire URI to get just the pathname 
    var uri = url.parse(request.url).pathname, query; 
     if (uri == "/account") //If it's mysite.com/account 
     { 
      request.setEncoding("utf8"); 
      request.content = ''; 
         //call account.whatever() to route to your account  functionality 
         //send the response from it 

     } 
      else if (uri == "/") //It's mysite.com 
      { 
         //call whatever you have in the current server.js 
      } 
}).listen(8080); 
+0

請更新答案,我在您回答之前幾秒鐘更改了問題。 – 2011-04-22 07:52:54

+0

我已更新我的回答 – neebz 2011-04-22 08:12:29

0

是的NodeJS一個守護進程。每次提出請求時都不會加載腳本。 您可以使用類似的東西:

var severs = require('server.js'), 
    accounts = require('accounts.js'); 

require('http').createServer(function (req, res) { 
    var path = require('url').parse(req.url).pathname; 
    res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'}); 

    if (path == '/account') { 
     res.end(accounts.run()); 
    } else { 
     res.end(severs.run()); 
    } 
}).listen(80); 
+0

.run()是一個真正的函數還是僅用於說明目的? – 2011-04-22 09:11:16

+0

插圖。閱讀關於在Nodejs中創建模塊的信息。 http://nodejs.org/docs/v0.4.6/api/modules.html – Emmerman 2011-04-22 09:19:19

0

這是更好地使用請求路由器 - 看connectexpress NPM模塊。手動路徑比較無法擴展 - 當您添加越來越多的URL時,它會將您的代碼變成噩夢。

對於獨立路由器,請參見clutch NPM模塊,但connect內部的路由器比較成熟,可以獨立使用。 expressconnect的擴展,所以它使用connect的路由器。