Cheng Mega Cheng Mega - 2 months ago 11
Node.js Question

How to fix ProcessBar to the top line in Nodejs CLI?

The terminal out is:
stdout
but actually this is what I really want:
progressbar will alway be the fist line,and got a response,then show it at below.

anyway to fix that?

enter image description here

Nodejs:

var request = require('request');
var ProgressBar = require('progress');
var year=[14,15,16];
var month=[1,2,3,4,5,6,7];
var bar = new ProgressBar('Processing [:bar] :percent', {
complete: '=',
incomplete: '-',
width: 30,
total: year.length*month.length,
});
/*-------------------------------------*/

function init(year,month){
check(year,month);
}

function check(year,month){
var options = { method: 'POST',
url: 'http://dev.site/date.php',
formData:{year:year,month:month}
};
request(options, function (error, response, body) {
if (error) {
console.log(error);;
}
if (body=='A task @') {
bar.tick();
console.log('\n'+body+year+':'+month);
}else{
bar.tick();
}
})
}
/*-------------------------------------*/

for (var i = 0; i < year.length; i++) {
for (var n = 0; n < month.length; n++) {
init(year[i],month[n]);
}
}

Answer

Using ansi-escapes you may be able to do this.

Here's a standalone version:

const ProgressBar = require('progress');
const ansiEscapes = require('ansi-escapes');
const write       = process.stdout.write.bind(process.stdout);

let bar = new ProgressBar('Processing [:bar] :percent', {
  complete   : '=',
  incomplete : '-',
  width      : 30,
  total      : 100
});

// Start by clearing the screen and positioning the cursor on the second line 
// (because the progress bar will be positioned on the first line)
write(ansiEscapes.clearScreen + ansiEscapes.cursorTo(0, 1));

let i = 0;
setInterval(() => {
  // Save cursor position and move it to the top left corner.
  write(ansiEscapes.cursorSavePosition + ansiEscapes.cursorTo(0, 0));

  // Update the progress bar.
  bar.tick();

  // Restore the cursor position.
  write(ansiEscapes.cursorRestorePosition);

  // Write a message every 10 ticks.
  if (++i % 10 === 0) {
    console.log('Now at', i);
  }

  // We're done.
  if (i === 100) {
    process.exit(0);
  }
}, 100);
Comments