Enhance Your Terminal Output with Log Update: A Powerful Node.js Library
log-update
is a Node.js library that allows you to get super clean and dynamic terminal output. It can be exceptionally useful when building command-line applications that require regular updates to the terminal. In this introduction, we will deep dive into some of its useful API functions with practical code snippets and an exemplary app to demonstrate its implementation.
Getting Started
npm install log-update
Basic Usage
Let’s start with a simple example of log-update:
const logUpdate = require('log-update');
const frames = ['-', '\\', '|', '/'];
let i = 0;
setInterval(() => {
const frame = frames[i = ++i % frames.length];
logUpdate(`
${frame} Loading...
`);
}, 80);
Clear the screen
const logUpdate = require('log-update');
logUpdate.clear();
Persist Output
Persist the current write, ensuring it remains after subsequent log update operations:
const logUpdate = require('log-update');
logUpdate('Initial log.');
logUpdate.done();
Multiple Streams
Log-update supports multiple streams. The following example demonstrates use with stdout and stderr:
const logUpdate = require('log-update');
const stream = process.stderr;
const render = () => {
logUpdate.create(stream)('Logging on stderr.');
};
setInterval(render, 1000);
A Practical Example
Here is a basic app that demonstrates some of the discussed APIs:
const logUpdate = require('log-update');
let frames = ['-', '\\', '|', '/'];
let i = 0;
const render = () => {
const frame = frames[i = ++i % frames.length];
logUpdate(`
${frame}
Downloading...
`);
};
const interval = setInterval(render, 80);
// Clear after 5 seconds
setTimeout(() => {
clearInterval(interval);
logUpdate.clear();
logUpdate.done();
}, 5000);
This basic app displays a loading spinner for 5 seconds and then clears the terminal output, persisting the final state.
Hash: 47fc3686c593b7111556e3943bb4a228e79e5edc7d96dc48bec0927c4bb8778a