3

我开始在 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)完成,是否会完全清除内存?

4

1 回答 1

2
  1. Node.js 是基于事件的,所有代码基本上都是事件的处理程序。V8 引擎将在处理程序中执行到结束任何同步代码,然后处理下一个事件。

    异步调用(网络/文件 IO)会将事件发布到另一个线程以执行阻塞 IO(这是在AFAIK 中,我可能错了)。然后,您的应用程序可以处理其他客户端。当 IO 任务完成时,会触发一个事件并调用您的回调函数。libev libeio

    这是 aync 调用流程的示例,模拟了处理客户端请求的 Node 应用程序:

    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 对象是否可以访问一块内存。我不确定它是否会在功能结束时积极清理内存。

参考:

这个 Google I/O演示讨论了 Chrome 的 GC 机制(因此是 V8)。

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

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

于 2013-09-24T16:27:17.823 回答