Introduction to Marked
Marked is a low-level markdown compiler that allows frequent parsing and compiling of markdown content. Its simplicity, efficiency, and compliance with commonly used markdown syntax make it popular among developers. Whether you are developing a markdown-supported web application or need seamless markdown to HTML conversion, Marked provides robust functionalities to fulfill these needs.
Installation
npm install marked
Using Marked
const marked = require('marked');
// Basic example
const markdown = '## Hello World!';
const html = marked(markdown);
console.log(html);
Setting Options
Marked supports setting options to customize the parsing process. You can control aspects such as breaks, gfm (GitHub Flavored Markdown), pedantic compliance, and more.
const marked = require('marked');
const options = {
gfm: true,
breaks: true,
};
marked.setOptions(options);
const markdown = 'First line \nSecond line';
const html = marked(markdown);
console.log(html);
Using Custom Renderer
One of the powerful features of Marked is the ability to create custom renderers. This allows you to override how elements are rendered.
const marked = require('marked');
const renderer = new marked.Renderer();
renderer.heading = function (text, level) {
return '' + text + ' ';
};
const markdown = '# Custom heading';
const html = marked(markdown, { renderer: renderer });
console.log(html);
Synchronous and Asynchronous Modes
Marked can be used both synchronously and asynchronously, depending on the demand of your application.
// Synchronous
const htmlSync = marked(markdown);
// Asynchronous
marked(markdown, function (err, html) {
if (err) throw err;
console.log(html);
});
Highlighting Code Syntax
If you want to highlight code blocks within your markdown, you can integrate Marked with a syntax highlighter like highlight.js.
const marked = require('marked');
const hljs = require('highlight.js');
marked.setOptions({
highlight: function(code) {
return hljs.highlightAuto(code).value;
}
});
const markdown = '```javascript\nconsole.log("Hello, World!");\n```';
const html = marked(markdown);
console.log(html);
Building a Simple Application
Let’s build a simple Node.js application that converts markdown entered by user to HTML and displays it.
const express = require('express');
const bodyParser = require('body-parser');
const marked = require('marked');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.send(
'<form method="post">' +
'<textarea name="markdown"></textarea>' +
'<button type="submit">Convert</button>' +
'</form>'
);
});
app.post('/', (req, res) => {
const markdown = req.body.markdown;
const html = marked(markdown);
res.send(html);
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
With the above code, you can create a basic web service that takes markdown input and returns the generated HTML.
Hash: d9b2fe68b6c253e250b14667fe79d988b4d2ac568f7fd62357330b906c30a49d