The Big Picture - moby/moby - Markdown

Markdown is a simple text-based markup language for creating formatted text on the web. The markdown-js library is a Markdown parser specifically for JavaScript projects. In this guide, we’ll explain why you might want to use markdown-js in your project and provide an example of how to use it.

Why Use markdown-js?

markdown-js is a versatile Markdown parser that offers several advantages over other options:

  1. Well-formed HTML: markdown-js produces well-formed HTML, ensuring proper nesting of em and strong elements and the ability to output both HTML and XHTML.
  2. Intermediate representation: It provides an intermediate representation (JsonML) of the parsed data, allowing for processing of the parsed data.
  3. Easily extensible: markdown-js is easily extensible to add new dialects without having to rewrite the entire parsing mechanics.
  4. Good test suite: It comes with a comprehensive test suite to ensure reliable and accurate parsing.

Installation

To use markdown-js in your project, follow these steps:

  1. Install the library using npm:
npm install markdown
  1. Optionally, install the md2html command-line tool:
npm install -g markdown

Usage

Node.js

To use markdown-js in a Node.js project, require the library and call its toHTML method:

const markdown = require('markdown').markdown;

const markdownText = 'Hello **World**!';
const htmlOutput = markdown.toHTML(markdownText);

console.log(htmlOutput);

Browser

You can also use markdown-js in the browser by including the library in a script tag:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Markdown Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/markdown/0.5.0/markdown.min.js"></script>
</head>
<body>
<textarea id="text-input" rows="6" cols="60"></textarea>
<div id="preview"></div>
<script>
const markdown = markdown.markdown;

const textInput = document.getElementById('text-input');
const preview = document.getElementById('preview');

textInput.addEventListener('input', () => {
preview.innerHTML = markdown.toHTML(textInput.value);
});
</script>
</body>
</html>

Command Line

You can convert Markdown to HTML using the md2html command-line tool:

# Read from a file
md2html doc.md > doc.html

# Or from stdin
echo 'Hello **World**!' | md2html

Conclusion

markdown-js is a powerful and flexible Markdown parser for JavaScript projects. Its ability to produce well-formed HTML, provide an intermediate representation, and be easily extensible makes it an excellent choice for handling Markdown in your projects.

For more information on Markdown and its usage, check out the following resources: