Convert Markdown to HTML in Node.js – .md to HTML

In this tutorial, I have covered how to convert markdown to HTML in Node.js.  Markdown is a light-weight markup language with plain-text formatting syntax that is designed to be easily converted to HTML and other formats. The simplicity of Markdown syntax makes it a popular choice for writing documentation, notes, and content for the web. Its readability and ease of use have made Markdown a standard among developers and non-technical writers alike.
Convert Markdown to HTML

Table of Contents

Understanding the Showdown Library

The Showdown library is a JavaScript utility that enables developers to convert Markdown to HTML programmatically within a Node.js environment. Showdown is easy to use, customizable, and adheres to Markdown standards. It provides a seamless way to render Markdown content as fully styled HTML without writing complex parsing code.

Installation of Showdown

The first step to using the Showdown library is to install it in your Node.js project. This can be done using the Node Package Manager (NPM). Simply run the following command in your project’s root directory:

npm install showdown

Setting Up Showdown in a Node.js Project

Once Showdown is installed, you can set it up in your Node.js application by requiring the library and creating a new instance of the converter. Here’s how to set it up:

// Require the Showdown library
const showdown = require('showdown');

// Create a converter function
function convertToHtml(markdownText) {
    let converter = new showdown.Converter(),
        html = converter.makeHtml(markdownText);

    return html;
}

// Call the function with your Markdown content
let myMarkdown = '# Hello Markdown!';
let myHtml = convertToHtml(myMarkdown);
console.log(myHtml);

Output:

<h1>Hello Markdown!</h1>

Converting Markdown to HTML Using Showdown

With the converter function set up, you can now pass Markdown strings to be converted into HTML. Below are some examples illustrating the conversion of different Markdown scenarios:

// Example 1: Headings
let headingMarkdown = '## This is a sub-heading';
let headingHtml = convertToHtml(headingMarkdown);
console.log(headingHtml);

// Example 2: Links
let linkMarkdown = '[Showdown](https://github.com/showdownjs/showdown)';
let linkHtml = convertToHtml(linkMarkdown);
console.log(linkHtml);

// Example 3: Images
let imageMarkdown = '![Alt Text](https://example.com/image.jpg)';
let imageHtml = convertToHtml(imageMarkdown);
console.log(imageHtml);

Handling Options (Optional):

Showdown allows you to customize the conversion process by providing options. For example, you can enable/disable certain features, customize header IDs, and more. Pass an options object when creating the converter. Here are some commonly used options:

  1. tables (boolean):
    • Default: false
    • Usage: Enables the conversion of tables in Markdown.
  2. strikethrough (boolean):
    • Default: false
    • Usage: Enables support for strikethrough text using the ~~ syntax.
  3. tasklists (boolean):
    • Default: false
    • Usage: Enables the creation of task lists using checkboxes [ ] and [x].
  4. noHeaderId (boolean):
    • Default: false
    • Usage: Disables the automatic generation of header IDs.
  5. ghCompatibleHeaderId (boolean):
    • Default: false
    • Usage: Generates header IDs compatible with GitHub.
  6. prefixHeaderId (string):
    • Default: "" (empty string)
    • Usage: Adds a prefix to header IDs.
  7. headerLevelStart (integer):
    • Default: 1
    • Usage: Specifies the starting level for headers.
  8. parseImgDimensions (boolean):
    • Default: false
    • Usage: Enables the parsing of image dimensions.
  9. simplifiedAutoLink (boolean):
    • Default: false
    • Usage: Converts plain URLs to clickable links.
  10. literalMidWordUnderscores (boolean):
    • Default: false
    • Usage: Allows underscores in the middle of words to be treated as literal underscores.
  11. literalMidWordAsterisks (boolean):
    • Default: false
    • Usage: Allows asterisks in the middle of words to be treated as literal asterisks.
  12. metadata (boolean):
    • Default: false
    • Usage: Extracts metadata from the document, such as title, date, and tags.
  13. splitAdjacentBlockquotes (boolean):
    • Default: false
    • Usage: Splits adjacent blockquotes into separate blocks.
  14. smoothLivePreview (boolean):
    • Default: false
    • Usage: Improves the live preview experience.
  15. smartIndentationFix (boolean):
    • Default: false
    • Usage: Fixes smart indentation issues in lists and blockquotes.
  16. disableForced4SpacesIndentedSublists (boolean):
    • Default: false
    • Usage: Disables the requirement of four spaces for indented sublists.
  17. emoji (boolean):
    • Default: false
    • Usage: Enables the conversion of emoji codes into corresponding emoji characters.
  18. underline (boolean):
    • Default: false
    • Usage: Enables parsing underscores as underlines.
const converterWithOptions = new showdown.Converter({ tables: true, strikethrough: true });

Handling Extensions (Optional):

Showdown supports extensions that provide additional functionality. You can enable extensions by including them when creating the converter. Below is the list of extensions.

  1. Tables:
    • Extension Name: table
    • Usage: Enables the use of tables in Markdown.
  2. Strikethrough:
    • Extension Name: strikethrough
    • Usage: Adds support for strikethrough text using the ~~ syntax.
  3. Task Lists:
    • Extension Name: tasklist
    • Usage: Allows the creation of task lists using checkboxes [ ] and [x].
  4. Emoji:
    • Extension Name: emoji
    • Usage: Converts emoji codes like :smile: into corresponding emoji characters.
  5. Footnotes:
    • Extension Name: footnotes
    • Usage: Adds support for footnotes in Markdown.
  6. MathJax:
    • Extension Name: mathjax
    • Usage: Enables the rendering of mathematical expressions using MathJax.
  7. KaTeX:
    • Extension Name: katex
    • Usage: Similar to MathJax, allows rendering of mathematical expressions using KaTeX.
  8. Highlight.js:
    • Extension Name: highlight
    • Usage: Integrates with Highlight.js to provide syntax highlighting for code blocks.
  9. Mermaid:
    • Extension Name: mermaid
    • Usage: Allows the inclusion of diagrams and flowcharts using the Mermaid syntax.
  10. TOC (Table of Contents):
    • Extension Name: toc
    • Usage: Generates a table of contents based on the headers in the Markdown document.
  11. Toc-Details:
    • Extension Name: toc-details
    • Usage: Extends the TOC extension to include collapsible/expandable details elements.
const converterWithExtensions = new showdown.Converter({ extensions: ['footnotes', 'highlight'] });

 

Troubleshooting Tips

When working with markdown conversion, some common challenges may include:

  • Improper rendering due to incorrect Markdown syntax.
  • Character escaping issues when converting to HTML.
  • Extension-related problems if specific Markdown features are needed.

To resolve these, ensure that the Markdown syntax is correct, and use the Showdown options and methods to customize the conversion process as needed.

Best Practices and Tips

Here are some best practices to ensure a smooth conversion process:

  • Always validate your Markdown to detect and fix syntax errors before conversion.
  • Explore and use Showdown extensions for additional Markdown features.
  • Test the HTML output to ensure it renders correctly across different browsers.

Summary

In this tutorial, we discussed the importance of converting Markdown to HTML and how the Showdown library makes this task efficient within a Node.js environment. By following the step-by-step instructions and code examples provided, you can effortlessly integrate Markdown conversion in your projects. The key takeaway is to understand the Markdown syntax well and utilize Showdown’s features to customize the HTML output. We encourage you to explore further and experiment with the Showdown library in your applications for a seamless content rendering experience.

References