2013-09-24 27 views
3

我開始寫的Node.js服務器,不知道是否我正在做的事情以正確的方式...有效的封閉結構中的node.js

基本上我的結構是這樣下面的僞代碼:

function processStatus(file, data, status) { 
... 
} 

function gotDBInfo(dbInfo) { 
    var myFile = dbInfo.file; 
    function gotFileInfo(fileInfo) { 
     var contents = fileInfo.contents; 
     function sentMessage(status) { 
      processStatus(myFile, contents, status); 
     } 
     sendMessage(myFile.name + contents, sentMessage); 
    } 
    checkFile(myFile, gotFileInfo); 
} 
checkDB(query, gotDBInfo); 

一般情況下,我想知道如果這是node.js的編寫正確的方式,更具體:

1)是VM足夠聰明運行「同時」(即切換上下文)每個回調之間不要掛斷大量連接的客戶端?

2)當運行垃圾收集,它會清除徹底,如果最後的回調(processStatus)完成了記憶?

回答

2
  1. 的Node.js是基於事件的,所有代碼基本上都是事件的處理程序。 V8引擎會執行處理程序中的任何同步代碼,然後處理下一個事件。

    異步調用(網絡/文件IO)將事件發佈到另一個線程做阻塞的IO(這是在 libev libeio據我所知,我可能是錯在這一點)。您的應用程序可以處理其他客戶端。 IO任務完成後,會觸發事件並調用您的回調函數。

    這裏的aync呼叫流程的例子,模擬節點的應用程序處理客戶端請求:

    onRequest(req, res) { 
        // we have to do some IO and CPU intensive task before responding the client 
    
        asyncCall(function callback1() { 
         // callback1() trigger after asyncCall() done it's part 
         // *note that some other code might have been executed in between* 
    
         moreAsyncCall(function callback2(data) { 
          // callback2() trigger after moreAsyncCall() done it's part 
          // note that some other code might have been executed in between 
    
          // res is in scope thanks to closure 
          res.end(data); 
    
          // callback2() returns here, Node can execute other code 
          // the client should receive a response 
          // the TCP connection may be kept alive though 
         }); 
    
         // callback1() returns here, Node can execute other code 
         // we could have done the processing of asyncCall() synchronously 
         // in callback1(), but that would block for too long 
         // so we used moreAsyncCall() to *yield to other code* 
         // this is kind of like cooperative scheduling 
        }); 
    
        // tasks are scheduled by calling asyncCall() 
        // onRequest() returns here, Node can execute other code 
    } 
    
  2. 當V8沒有足夠的內存,它會做垃圾回收。它知道現場JavaScript對象是否可以訪問大塊內存。我不確定在功能結束時是否會積極清理內存。

參考文獻:

This Google I/O陳述中討論鉻(因此V8)的GC機制。

http://platformjs.wordpress.com/2010/11/24/node-js-under-the-hood/

http://blog.zenika.com/index.php?post/2011/04/10/NodeJS

+0

對於點#1澄清,這很重要,如果回調嵌套或者是完全不相干的? 對於點#2,我的意思是垃圾收藏 - 澄清以上,由於 – davidkomer

+0

@davidkomer#1是的,沒有。如果你需要包含數據(你在'gotFileInfo'中通過訪問在包裝函數中定義的'myFile'來完成的操作,它就是重要的。你使用命名的方法來定義函數,我不能肯定地說如果是這樣的話 - 如果是這樣的話,並且爲你保留範圍更多的權力,我強烈建議你通過定義匿名函數來嵌套回調函數對外部函數(做一個閉包)的要求:var someFunk = function(){/ *我沒有名字* /};'然後用'someFunk'在回調傳遞 –

+0

@davidkomer坦白地說,你的示例代碼似乎「太同步」你必須讓IO或異步處理,以適應範式。 Node.js的 – leesei