2013-09-24 25 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