Introduction to cli-highlight
cli-highlight
is a powerful tool designed to highlight code snippets in a command line interface. It enhances readability and provides a visually appealing way to present code.
Useful APIs and Examples
1. highlight
Highlight code with the default settings.
const { highlight } = require('cli-highlight');
const code = `const greet = () => {
console.log('Hello, World!');
}`;
console.log(highlight(code));
2. highlightAuto
Automatically detect the language and highlight accordingly. This is useful when you don’t know the language in advance.
const { highlightAuto } = require('cli-highlight');
const code = `function greet() {
return 'Hello, World!';
}`;
console.log(highlightAuto(code).value);
3. setTheme
Change the theme of your code highlighting.
const { setTheme, highlight } = require('cli-highlight');
setTheme({
keyword: 'blue',
string: 'green',
number: 'red'
});
const code = `const age = 30; console.log('Age:', age);`;
console.log(highlight(code));
4. listLanguages
List all the supported languages.
const { listLanguages } = require('cli-highlight');
console.log(listLanguages());
CLI App Example
Here’s an example of a command-line application that uses cli-highlight
to format and highlight code snippets provided by the user.
// app.js const { highlight } = require('cli-highlight'); const fs = require('fs');
function showHighlightedCode(filePath) {
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) throw err;
console.log(highlight(data));
});
}
const filePath = process.argv[2]; if (filePath) {
showHighlightedCode(filePath);
} else {
console.error('Please provide a file path');
}
Save the above code in a file named app.js
. You can run the application with the following command:
node app.js path/to/your/codefile.js
This will read the content of the provided file, highlight the code, and display it in the terminal.
Hash: 74d733bab3a8fdea9b4ed1bbd86e1fa91d9fa088c6c059d73e416abbaa40b793