Back to all posts
javascriptnpmmarkdownhtmlweb-developmentNovember 28, 20246 min read

How to Transform Markdown into HTML Using JavaScript and npm

Markdown has become the go-to syntax for writing lightweight and easily readable formatted text. Whether documenting a project, writing a blog post, or creating content for a web application, Markdown offers simplicity and flexibility. However, when it comes to displaying this content on the web, you need to convert it into HTML—a format browsers understand.

In this article, we'll explore how to transform Markdown into HTML using JavaScript and npm. We'll leverage the power of the marked package, a fast and robust Markdown parser. By the end of this guide, you'll be able to seamlessly convert Markdown content into HTML, whether you're building a web application or automating content processing. Let's dive in!

Prerequisites

Before we begin, make sure you have the following:

  1. Node.js and npm installed: Node.js allows you to run JavaScript outside a browser, and npm (Node Package Manager) is used to install packages like marked. If you don't have them installed, download them from nodejs.org and follow the installation steps.
  2. A basic understanding of JavaScript: You should know how to write and run simple JavaScript code.
  3. A code editor: Any text editor will work, but something like Visual Studio Code makes writing and managing code easier.

Installing the marked package

Once you have created a folder, now we need to install marked package using npm.

npm init -y
npm install marked

Setting Up the Project

To start, let's create a simple project that reads a Markdown file and converts it into HTML using JavaScript.

Step 1: Create a Sample Markdown File

Create a file named example.md:

### Markdown to HTML

- This is a markdown file example.

```javascript
function sum(int a, int b) {
 return a + b;
}

Step 2: Script using Javascript

Create a file named render-markdown.js:

const fs = require('fs');
const { marked } = require('marked'); // Use named import
const http = require('http');
const path = require('path');

// Path to your markdown file
const markdownFilePath = path.join(__dirname, 'example.md');

// Function to convert Markdown to HTML
function renderMarkdownToHtml(markdownFilePath) {
    const markdown = fs.readFileSync(markdownFilePath, 'utf8');
    return marked(markdown); // Call the `marked` function
}

// Create an HTTP server to serve the HTML
http.createServer((req, res) => {
    if (req.url === '/') {
        const htmlContent = renderMarkdownToHtml(markdownFilePath);
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end(`
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>Markdown Viewer</title>
                <style>
                    body {
                        font-family: Arial, sans-serif;
                        margin: 20px;
                    }
                </style>
            </head>
            <body>
                <div id="content">${htmlContent}</div>
            </body>
            </html>
        `);
    } else {
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('404 Not Found');
    }
}).listen(3000, () => {
    console.log('Server is listening on port 3000');
});

Step 3: Run the Script

Open your terminal and navigate to the folder containing example.md and render-markdown.js. Run the following command to start the server:

node render-markdown.js

Open a browser and go to http://localhost:3000. You'll see the content of example.md rendered as HTML!

Note: In this example, both example.md and render-markdown.js are in the same folder. If your files are organized differently, update the path in markdownFilePath accordingly.

Surprise! Render Markdown with Just One Line

Here's a simpler way to render Markdown files directly in your browser without writing a server script. With the zero-md web component, you can display a Markdown file with a single HTML tag!

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <meta name="viewport" content="width=device-width, initial-scale=1.0">  
    <title>Markdown Viewer with zero-md</title>  
</head>  
<body>  

    <!-- Include the polyfill for web components -->  
    <script src="https://cdn.jsdelivr.net/npm/@webcomponents/webcomponentsjs@2/webcomponents-loader.min.js"></script>  

    <!-- Load zero-md module -->  
    <script type="module" src="https://cdn.jsdelivr.net/gh/zerodevx/zero-md@1/src/zero-md.min.js"></script>  

    <!-- Render the markdown file -->  
    <zero-md src="example.md"></zero-md>  

</body>  
</html>  

How It Works

  1. The <zero-md> tag fetches the specified Markdown file (example.md) and automatically converts it into HTML.
  2. It's perfect for static sites where you want to render Markdown quickly without running JavaScript or setting up a server.

Conclusion

Converting Markdown to HTML has always been challenging! Whether you're building a robust server-side application with marked or taking advantage of the simplicity of <zero-md> for static rendering, you now have the tools to display Markdown beautifully on the web.

For dynamic and programmatic use, marked is a powerful choice. On the other hand, <zero-md> offers a seamless, no-code solution for quick rendering. Pick the method that best suits your project and bring your Markdown content to life with ease!