2017-04-06 30 views
1

你好,我目前使用的網站「Codeschool.com」,我覺得教官代碼中有一個無限循環中的節點/ Javascript代碼,但我不能肯定。這個While循環如何結束? - 節點編號

下面是代碼:

http.createServer(function(request, response) { 
    response.writeHead(200); 
    request.on('readable', function() { 
    var chunk = null; 
    while(null !==(chunk = request.read())) { 
     response.write(chunk); 
    } 
    }); 
    request.on('end', function() { 
    response.end(); 
    }); 
}).listen(8080) 

教員說,這個代碼是類似於使用request.pipe(響應);

我理解這個概念,但什麼扔我一個循環(沒有雙關語意)是這個while循環,它是如何了得?

+1

當'request.read()' null'分配''到chunk',條件不滿足,它停止,因爲它是現在'=== null'。 – 2017-04-06 00:11:40

回答

0

request.read()每次調用時會返回一部分可用數據,直到沒有更多數據要返回爲止,在這種情況下返回null

在這一點上,chunk也等於null並且由於分配是返回所分配的值的表達式,條件爲假,併爲此while循環結束時:

while (null !== (chunk = null)) { ... }