Being totally new into node.js environment and philosophy i would like answers to few questions. I had downloaded the node.js for windows installer and also node package man
In my case I did it to loop for ever and show in the console a number ever in a single line:
class Status {
private numberOfMessagesInTheQueue: number;
private queueName: string;
public constructor() {
this.queueName = "Test Queue";
this.numberOfMessagesInTheQueue = 0;
this.main();
}
private async main(): Promise<any> {
while(true) {
this.numberOfMessagesInTheQueue++;
await new Promise((resolve) => {
setTimeout(_ => resolve(this.showResults(this.numberOfMessagesInTheQueue)), 1500);
});
}
}
private showResults(numberOfMessagesInTheQuee: number): void {
console.clear();
console.log(`Number of messages in the queue ${this.queueName}: ${numberOfMessagesInTheQuee}.`)
}
}
export default new Status();
When you run this code you will see the same message "Number of messages in the queue Test Queue: 1." and the number changing (1..2..3, etc).
You can use the readline
module:
readline.cursorTo(process.stdout, 0, 0)
moves the cursor to (0, 0).
readline.clearLine(process.stdout, 0)
clears the current line.
readline.clearScreenDown(process.stdout)
clears everything below the cursor.
const READLINE = require('readline');
function clear() {
READLINE.cursorTo(process.stdout, 0, 0);
READLINE.clearLine(process.stdout, 0);
READLINE.clearScreenDown(process.stdout);
}
Based on sanatgersappa's answer and some other info I found, here's what I've come up with:
function clear() {
var stdout = "";
if (process.platform.indexOf("win") != 0) {
stdout += "\033[2J";
} else {
var lines = process.stdout.getWindowSize()[1];
for (var i=0; i<lines; i++) {
stdout += "\r\n";
}
}
// Reset cursur
stdout += "\033[0f";
process.stdout.write(stdout);
}
To make things easier, I've released this as an npm package called cli-clear.
On mac, I simply use Cmd + K to clear the console, very handy and better than adding codes inside your project to do it.
Belated, but ctrl+l works in windows if you're using powershell :) Powershell + chocolatey + node + npm = winning.
Ctrl + L This is the best, simplest and most effective option.