High-Speed Markdown Parser and Compiler – Marked.js Tutorial

Introduction to Marked.js

Marked.js is a fast, full-featured Markdown parser and compiler, built for speed. It converts Markdown into HTML, allowing developers to easily display styled text on web pages. Before diving into the usage of Marked.js, let’s explore how to set it up and get started.

Installation

To install Marked.js, you can use npm, the Node.js package manager. Simply run the following command in your terminal:

npm install marked

Using the CLI

The Marked command-line interface (CLI) is a useful way to parse markdown from your terminal. After installing Marked, you can use it directly as shown below.

marked -o output.html input.md

This command will output the HTML result to ‘output.html’ after parsing ‘input.md’.

Example: Specifying Markdown Options

You can also specify options in the CLI to customize the output:

marked -s "# Hello World" --gfm true --breaks true

This example enables GitHub Flavored Markdown (GFM) and adds breaks on new lines.

Compiling Markdown in Node.js

To compile markdown using Marked in a Node.js script, you can include the library and use it to parse markdown strings as shown below:

const marked = require('marked');
let markdownString = 'I am using **marked**.';
console.log(marked(markdownString));

Example: Using Renderer

You can also use a custom renderer to modify the output:

const renderer = new marked.Renderer();
renderer.link = (href, title, text) => `<a href="${href}" rel="nofollow">${text}</a>`;

marked.setOptions({
  renderer: renderer
});

console.log(marked('[Marked](https://github.com/markedjs/marked)'));

Compiling Markdown in the Browser

For browser environments, you can link to the Marked.js library and then use it within your HTML:

<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script>
  document.getElementById('content').innerHTML =
    marked('# Marked in the browser\n\nRendered by **marked**.');
</script>

Add this script after an HTML element with id ‘content’ and it will insert the resulting HTML into the page.

References

Conclusive Summary

This article has guided you through the different possibilities offered by Marked.js, a robust Markdown parser and compiler. You’ve learned how to install the library, use it via CLI, and apply it in both Node.js and browser environments. By utilizing Marked.js, you can enhance your applications with efficient and customizable markdown rendering.