2017-09-27 40 views
0

我使用下面的代碼來解析一個Ascii Stl文件(帶有頂點座標)並輸出每個頂點的座標。雖然STL文件僅僅是30M左右,當節點腳本運行,有600M左右MEM留在系統中形成控制檯nodejs函數耗盡了所有內存?

[email protected]:~/node$ ls -l DNA_mit_Anhnger.stl 
-rw-r--r-- 1 roofe roofe 34964929 Sep 27 09:50 DNA_mit_Anhnger.stl 

~/node$ node test.js DNA_mit_Anhnger.stl 
vertex 4.893074e-001 8.750000e+000 2.695633e-001 
free mem:: 557mb 
vertex 5.357143e-001 8.750000e+000 3.077444e-001 
free mem:: 557mb 

,而作爲運行MEM腳本將被耗盡了,直至出現系統殺死腳本

Killed 
[email protected]:~/node$ 

當腳本運行時,我還用另一個終端來檢查系統MEM,(這裏是2GB的紀念品Ubuntu16服務器LTS VMvare機)

[email protected]:~/node$ ps v 

    PID TTY  STAT TIME MAJFL TRS DRS RSS %MEM COMMAND 
    1064 tty1  S+  0:00  1 975 21492  4 0.0 -bash 
18623 pts/1 Ss+ 0:00 715 975 21612  4 0.0 -bash 
19140 pts/2 Ss  0:00 1352 975 21604 16 0.0 -bash 
19482 pts/3 Ss  0:00 2594 975 21596 1124 0.1 -bash 
77681 pts/2 Rl+ 0:19 120131 10894 2090529 737716 73.9 node 

這裏是腳本,

var fs = require("fs"); 
var os = require('os'); 
var data = fs.readFileSync(process.argv[2]); 
var parseAscii = function(data) { 
    var offset = 0; 
    var str = ''; 
    while(offset = data.indexOf('vertex', ++offset)) { 
     str = data.substr(offset, data.indexOf('\n', offset) - offset); 
     console.log(str); 
     console.log('free mem:: ' + Math.ceil(os.freemem()/(1024*1024)) + 'mb'); 
    } 
    console.log('finish'); 
} 
parseAscii(data.toString()); 

的Ascii STL文件格式是這樣的,

solid ascii 
    facet normal -6.343656e-001 -5.556834e-002 7.710334e-001 
    outer loop 
     vertex 4.893074e-001 8.750000e+000 2.695633e-001 
     vertex 5.357143e-001 8.750000e+000 3.077444e-001 
     vertex 5.077149e-001 8.785503e+000 2.872667e-001 
    endloop 
    endfacet 
    facet normal -7.010786e-001 -9.853018e-002 7.062440e-001 
    outer loop 
     vertex 4.616061e-001 8.782279e+000 2.410454e-001 
     vertex 5.077149e-001 8.785503e+000 2.872667e-001 
     vertex 4.526215e-001 8.846208e+000 2.410454e-001 
    endloop 
    endfacet 

我已經對整個下午的發行工作,但一無所獲,它幾乎驅動我瘋了。

+1

什麼時候你的循環會中斷?如果indexOf沒有找到字符串,它將返回-1。 '-1'評估爲'true' – sidgate

+0

是的,它會導致無限循環。我也不知道爲什麼它會耗盡所有的記憶。 –

回答

2

您的循環在任何情況下都不會中斷。當處理最後的vertex時,indexOf返回-1,如果它沒有找到任何東西。所以偏移設置爲-1,while循環無限地迭代。所有你需要的是添加一個檢查比較-1

while((offset = data.indexOf('vertex', ++offset))!=-1) 
+0

謝謝。我對js沒有太多經驗。我沒有意識到'indexOf()'在找不到像其他某種編程語言的'substr()'返回False時不同的輸出。 –

+0

我也有一些困惑,雖然無限的while循環,但不應該耗盡更多的mem作爲進行中。應該只在函數中分配固定內存。 –