Introduction to Marked Terminal
Marked Terminal is a fantastic markdown parser that allows developers to render markdown in the terminal. Whether you’re building sophisticated command-line applications or simple documentation tools, Marked Terminal provides all the functionalities you need. Below, we’ll explore a variety of its APIs, showcasing their capabilities with code snippets, and ultimately build a small CLI app using these APIs.
Installation
npm install marked-terminal marked
Basic Usage
The basic usage of Marked Terminal involves parsing markdown strings and displaying them in the terminal. Here’s an example:
const marked = require('marked');
const TerminalRenderer = require('marked-terminal');
// Configure marked to use the TerminalRenderer
marked.setOptions({
renderer: new TerminalRenderer()
});
// Example markdown content
const markdown = '# Hello World\n\nThis is a **bold** text.';
// Display the markdown content in the terminal
console.log(marked(markdown));
Advanced Configuration
Marked Terminal supports various configuration options to customize its rendering. Here’s how you can configure it:
const renderer = new TerminalRenderer({
showSectionPrefix: false,
tab: 4,
unescape: false,
emoji: true
});
marked.setOptions({
renderer: renderer
});
const content = '# Welcome to Marked Terminal\n\n- Item 1\n- Item 2 :rocket:';
console.log(marked(content));
Using Custom Styles
To enhance the readability, you can apply custom styles. Here’s an example:
const rendererStyled = new TerminalRenderer({
headings: ['underline', 'green'],
firstHeading: ['underline', 'bold', 'cyan']
});
marked.setOptions({
renderer: rendererStyled
});
const contentStyled = '# Custom Style Heading\n\nSome content here with *italic* and **bold** text.';
console.log(marked(contentStyled));
An Integrated CLI App
Let’s create a simple CLI app that uses these features to display Markdown-formatted text:
#!/usr/bin/env node
const fs = require('fs');
const marked = require('marked');
const TerminalRenderer = require('marked-terminal');
marked.setOptions({
renderer: new TerminalRenderer()
});
const filePath = process.argv[2];
if (!filePath) {
console.error('Please provide a markdown file path.');
process.exit(1);
}
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error('Error reading markdown file:', err);
process.exit(1);
}
console.log(marked(data));
});
Save the above script to a file named mdviewer.js
, and make it executable:
chmod +x mdviewer.js
Now you can view any markdown file in the terminal by running:
./mdviewer.js path/to/markdown-file.md
With this CLI tool, you can easily render and view markdown files directly in your terminal, enhancing your productivity and making it easier to manage documentation and notes.
Explore more about Marked Terminal and integrate it into your projects to unlock more functionalities!
Hash: 5f262654f54aa7bbb68300f1c32e73a6c9f6c4c4ab6cb77c02a676ee2adc2e56