我正在研究cpu heavy单线程控制台实用程序。我在一个同步调用中做cpu繁重的工作(即没有像这样的回调和废话),但是,显然,节点,出于某些疯狂的原因正异步输出到终端。有没有办法解决这个问题?我正在尝试显示一个进度条,但它完全没用,因为它在cpu工作完成后显示它,节点除了后面的打印之外什么都不做(在那一点没有意义,也延迟退出)。
以下是我正在使用的进度条的代码:
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 :(得分:0)
如果您想立即查看,可以写入process.stderr。
请参阅doc:https://nodejs.org/api/process.html#process_process_stderr
答案 1 :(得分:0)
找出最佳方法:
var _fs = require('fs');
process.stdout.write = function(data) {
try {
_fs.writeSync(1, data);
} catch (e) {
process.stdout.write(data);
}
};