我开始在 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)结束,是否会彻底清空内存?
最佳答案
Node.js 是基于事件的,所有代码基本上都是事件的处理程序。 V8 引擎将执行到结束处理程序中的任何同步代码,然后处理下一个事件。
异步调用(网络/文件 IO)将向另一个线程发布事件以执行阻塞 IO(在
libev
libeio
AFAIK ,我对此可能是错误的)。然后您的应用程序可以处理其他客户端。 IO 任务完成后,将触发一个事件并调用您的回调函数。这是一个 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 }
当V8没有足够的内存时,它会进行垃圾回收。它知道实时 JavaScript 对象是否可以访问一 block 内存。我不确定它是否会在函数结束时主动清理内存。
引用资料:
This Google I/O演示文稿讨论了 Chrome 的 GC 机制(因此是 V8)。
http://platformjs.wordpress.com/2010/11/24/node-js-under-the-hood/
关于javascript - node.js 中高效的闭包结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18986812/