Examples
This page provides practical examples of using the Markdown to HTML Converter for various real-world scenarios.
Basic Examples
Simple Document
Input:
# Welcome to Our Platform
This is a **simple document** with basic formatting.
## Features
- Easy to use
- Fast conversion
- Live preview
Visit our [website](https://example.com) for more information.
Output:
<h1>Welcome to Our Platform</h1>
<p>This is a <strong>simple document</strong> with basic formatting.</p>
<h2>Features</h2>
<ul>
<li>Easy to use</li>
<li>Fast conversion</li>
<li>Live preview</li>
</ul>
<p>Visit our <a href="https://example.com">website</a> for more information.</p>
Code Documentation
Input:
# API Documentation
## Authentication
Use the following endpoint for authentication:
```javascript
const response = await fetch('/api/auth', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: 'user@example.com',
password: 'password123',
}),
});
```
Response Format
The API returns a JSON response:
{
"success": true,
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"expires": "2024-12-31T23:59:59Z"
}
**Output:**
```html
<h1>API Documentation</h1>
<h2>Authentication</h2>
<p>Use the following endpoint for authentication:</p>
<pre><code class="language-javascript">const response = await fetch('/api/auth', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: 'user@example.com',
password: 'password123'
})
});</code></pre>
<h3>Response Format</h3>
<p>The API returns a JSON response:</p>
<pre><code class="language-json">{
"success": true,
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"expires": "2024-12-31T23:59:59Z"
}</code></pre>
Advanced Examples
GitHub-Style README
Input:
# Project Name
[](https://travis-ci.org/user/repo)
[](https://opensource.org/licenses/MIT)
A powerful tool for converting Markdown to HTML.
## Table of Contents
- [Installation](#installation)
- [Usage](#usage)
- [API Reference](#api-reference)
- [Contributing](#contributing)
- [License](#license)
## Installation
```bash
npm install markdown-to-html
```
Usage
Basic Usage
import { convertMarkdown } from 'markdown-to-html';
const html = await convertMarkdown('# Hello World');
console.log(html); // <h1>Hello World</h1>
Advanced Usage
const html = await convertMarkdown(markdown, {
outputFormat: 'xhtml',
sanitize: true,
gfm: true,
});
API Reference
Method | Description | Parameters |
---|---|---|
convertMarkdown | Convert Markdown to HTML | markdown: string, options?: object |
sanitizeHtml | Sanitize HTML content | html: string |
validateUrl | Validate URL safety | url: string |
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
### Technical Documentation
**Input:**
```markdown
# System Architecture
## Overview
Our system follows a microservices architecture with the following components:
```mermaid
graph TB
A[Client] --> B[API Gateway]
B --> C[Auth Service]
B --> D[User Service]
B --> E[Content Service]
C --> F[Database]
D --> F
E --> F
Components
API Gateway
- Purpose: Entry point for all client requests
- Technology: Node.js with Express
- Port: 3000
Authentication Service
- Purpose: Handles user authentication and authorization
- Technology: Node.js with JWT
- Port: 3001
User Service
- Purpose: Manages user profiles and preferences
- Technology: Node.js with MongoDB
- Port: 3002
Content Service
- Purpose: Handles content creation and retrieval
- Technology: Node.js with PostgreSQL
- Port: 3003
Database Schema
Users Table
CREATE TABLE users (
id UUID PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
password_hash VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
Content Table
CREATE TABLE content (
id UUID PRIMARY KEY,
user_id UUID REFERENCES users(id),
title VARCHAR(255) NOT NULL,
body TEXT NOT NULL,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
API Endpoints
Authentication
POST /auth/login
POST /auth/login HTTP/1.1
Content-Type: application/json
{
"email": "user@example.com",
"password": "password123"
}
Response:
HTTP/1.1 200 OK
Content-Type: application/json
{
"success": true,
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"id": "123e4567-e89b-12d3-a456-426614174000",
"email": "user@example.com"
}
}
Content Management
GET /content
Retrieve all content for the authenticated user.
POST /content
Create new content.
PUT /content/:id
Update existing content.
DELETE /content/:id
Delete content.
Error Handling
The API uses standard HTTP status codes:
200 OK
- Request successful201 Created
- Resource created400 Bad Request
- Invalid request data401 Unauthorized
- Authentication required403 Forbidden
- Access denied404 Not Found
- Resource not found500 Internal Server Error
- Server error
Security Considerations
Important: Always validate input data and sanitize HTML content.
Input Validation
- Validate all incoming data
- Use proper data types
- Implement rate limiting
Output Sanitization
- Sanitize HTML content
- Validate URLs
- Prevent XSS attacks
Performance Optimization
Caching Strategy
- Redis for session storage
- CDN for static assets
- Database query optimization
Monitoring
- Application performance monitoring
- Error tracking and logging
- Health check endpoints
## Real-World Use Cases
### Blog Post
**Input:**
```markdown
# Getting Started with Vue.js 3
*Published on December 15, 2024*
Vue.js 3 has brought many exciting new features and improvements. In this post, we'll explore the key changes and how to get started with the latest version.
## What's New in Vue.js 3?
### Composition API
The Composition API is now the recommended approach for building Vue applications:
```vue
<template>
<div>
<h1>{{ title }}</h1>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
const title = ref('Hello Vue 3!')
const count = ref(0)
const increment = () => {
count.value++
}
</script>
Performance Improvements
- Faster rendering: Up to 2x faster than Vue 2
- Smaller bundle size: Tree-shaking support
- Better TypeScript support: Built-in TypeScript support
Migration Guide
If you're upgrading from Vue 2, here's what you need to know:
- Breaking Changes
- Global API changes
- Component API changes
- Template syntax updates
- Migration Steps
- Update dependencies
- Run migration helper
- Update component code
- Test thoroughly
Conclusion
Vue.js 3 represents a significant step forward for the framework. The Composition API provides better code organization, and the performance improvements make it an excellent choice for modern web applications.
Resources:
### Email Template
**Input:**
```markdown
# Welcome to Our Platform!
Dear {{ user.name }},
Thank you for signing up for our platform! We're excited to have you on board.
## Getting Started
Here are some quick steps to get you started:
1. **Complete your profile** - Add a photo and bio
2. **Explore features** - Check out our main features
3. **Connect with others** - Join our community
## Key Features
- ✅ **Real-time collaboration**
- ✅ **Advanced analytics**
- ✅ **Custom integrations**
- ✅ **24/7 support**
## Need Help?
If you have any questions, don't hesitate to reach out:
- **Email**: support@example.com
- **Live Chat**: Available 24/7
- **Documentation**: [help.example.com](https://help.example.com)
## What's Next?
- [Complete your profile](https://app.example.com/profile)
- [Explore features](https://app.example.com/features)
- [Join community](https://community.example.com)
---
*This email was sent to {{ user.email }}. If you didn't sign up for our platform, please ignore this email.*
Best regards,
The Example Team
Integration Examples
React Component
import React, { useState, useEffect } from 'react';
import { convertMarkdown } from 'markdown-to-html';
function MarkdownEditor() {
const [markdown, setMarkdown] = useState('');
const [html, setHtml] = useState('');
useEffect(() => {
const convert = async () => {
try {
const result = await convertMarkdown(markdown, {
sanitize: true,
gfm: true,
});
setHtml(result);
} catch (error) {
console.error('Conversion failed:', error);
}
};
convert();
}, [markdown]);
return (
<div className="markdown-editor">
<div className="input-panel">
<textarea
value={markdown}
onChange={(e) => setMarkdown(e.target.value)}
placeholder="Enter Markdown..."
/>
</div>
<div className="output-panel">
<div dangerouslySetInnerHTML={{ __html: html }} />
</div>
</div>
);
}
Vue Component
<template>
<div class="markdown-converter">
<div class="input-section">
<textarea v-model="markdown" placeholder="Enter Markdown..." @input="convertMarkdown" />
</div>
<div class="output-section">
<div v-html="html"></div>
</div>
</div>
</template>
<script setup>
import { ref, watch } from 'vue';
import { convertMarkdown } from 'markdown-to-html';
const markdown = ref('');
const html = ref('');
const convertMarkdown = async () => {
try {
const result = await convertMarkdown(markdown.value, {
sanitize: true,
gfm: true,
});
html.value = result;
} catch (error) {
console.error('Conversion failed:', error);
}
};
watch(markdown, convertMarkdown);
</script>
Node.js Server
const express = require('express');
const { convertMarkdown } = require('markdown-to-html');
const app = express();
app.use(express.json());
app.post('/convert', async (req, res) => {
try {
const { markdown, options = {} } = req.body;
const html = await convertMarkdown(markdown, {
sanitize: true,
gfm: true,
...options,
});
res.json({ html });
} catch (error) {
res.status(400).json({ error: error.message });
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Best Practices
1. Content Structure
- Use proper heading hierarchy (H1 → H2 → H3)
- Include alt text for images
- Use semantic HTML elements
2. Security
- Always enable HTML sanitization
- Validate user input
- Use HTTPS for external links
3. Performance
- Optimize images before embedding
- Use reference-style links for repeated URLs
- Consider document size for real-time conversion
4. Accessibility
- Include proper heading structure
- Use descriptive link text
- Ensure color contrast compliance
Next Steps
Explore more:
- API Reference for technical details
- Security Considerations for safe usage
- FAQ for common questions