2016-05-13 60 views
-1

我正在研究cpu重型單線程控制檯實用程序。我在一次同步調用中做了cpu繁重的工作(即沒有這樣的回調和廢話),然而,顯然,節點由於某種瘋狂的原因正在異步地輸出到終端。有什麼辦法可以解決這個問題嗎?我試圖顯示一個進度條,但是它完全沒有用處,因爲它在cpu工作完成後顯示它並且節點除了打印之外什麼都沒做(在這一點上沒有意義,並且也延遲了退出)。如何同步寫入process.stdout?

這裏是我的進度條代碼我使用:

function ProgressBar(total, displayLen, prompt) { /**class*/ 
    this.prompt = prompt; 
    this.total = total; 
    this.displayLen = displayLen; 
    this.perctf = 100.0/total; 
    this.displayf = 100.0/displayLen; 
    this.percprog = 0; 
    this.displayprog = 0; 

    this.laststr = ""; 
    this.dots = ""; 
    this.cpgrinc = 0; 
    this.lastdisplayc = 0; 
} 

ProgressBar.prototype.update = function() { 
    this.percprog += this.perctf; 
    this.displayprog += this.perctf; 
    if (this.displayprog > this.displayf) { 
     this.dots += "."; 
     this.displayprog = 0; 
    } 
    this.cpgrinc = (this.cpgrinc + 1) % 4; 

    this.clear(); 
    this.laststr = this.prompt + " [" + this.dots; 
    this.write(this.laststr + " " + 
     this.percprog.toFixed() + "%] " + this.indicator()); 
}; 

ProgressBar.prototype.clear = function() { 
    var str = ""; 
    for (var i = 0; i < this.lastdisplayc; i++) { 
     str += "\b"; 
    } 
    process.stdout.write(str); 
}; 

ProgressBar.prototype.write = function(data) { 
    process.stdout.write(data); 
    this.lastdisplayc = data.length; 
}; 

ProgressBar.prototype.indicator = function() { 
    switch (this.cpgrinc) { 
     case 0: 
      return "-"; 
     case 1: 
      return "\\"; 
     case 2: 
      return "|"; 
     case 3: 
      return "/"; 
    } 
}; 

ProgressBar.prototype.run = function(callback) { 
    var that = this; 
    callback(function() { 
     that.update(); 
    }); 
    this.clear(); 
    process.stdout.write(this.laststr + "] 100% Finished\n"); 
}; 

ProgressBar.prototype.runAsync = function(callback) { 
    var that = this; 
    callback(function() { 
     that.update(); 
    }, function() { 
     that.clear(); 
     process.stdout.write(that.laststr + "] 100% Finished\n"); 
    }); 
}; 

回答

0

想出最好的辦法:

var _fs = require('fs'); 
process.stdout.write = function(data) { 
    try { 
     _fs.writeSync(1, data); 
    } catch (e) { 
     process.stdout.write(data); 
    } 
};