Introduction to `marked`
`marked` is a low-level markdown compiler for parsing markdown without caching or blocking for long periods of time.
It is built for speed and works well with large markdown files, making it an excellent choice for high performance applications.
Basic Usage
const marked = require('marked'); const markdownString = '# Hello World!'; const htmlString = marked(markdownString); console.log(htmlString); //Hello World!
Using Options
`marked` offers various options to customize the rendering:
const markdownString = '# Hello World!\n\nThis is a paragraph with **bold text**.'; const options = { gfm: true, tables: true, breaks: true, }; const htmlString = marked(markdownString, options); console.log(htmlString); //Hello World!
This is a paragraph with bold text.
Using Custom Renderer
You can use a custom renderer to apply your own styles:
const renderer = new marked.Renderer(); renderer.heading = function(text, level) { return '' + text + ' '; }; const markdownString = '# Hello World!'; const htmlString = marked(markdownString, { renderer: renderer }); console.log(htmlString); //Hello World!
Using Plugins
You can extend `marked` using plugins:
const markdownString = '# Hello {name}'; const options = { plugins: [ function(markdown) { return markdown.replace(/{name}/g, 'World'); } ] }; const htmlString = marked(markdownString, options); console.log(htmlString); //Hello World
Building a Simple App with `marked`
Let’s build a simple Node.js application that uses `marked` to convert markdown to HTML:
const express = require('express'); const marked = require('marked'); const bodyParser = require('body-parser'); const app = express(); app.use(bodyParser.text({ type: 'text/markdown' })); app.post('/convert', (req, res) => { const markdownString = req.body; const htmlString = marked(markdownString); res.send(htmlString); }); app.listen(3000, () => { console.log('App is running on http://localhost:3000'); });
Now you can run this app and send a POST request with markdown text to `http://localhost:3000/convert` to get the converted HTML in the response.
Hash: d9b2fe68b6c253e250b14667fe79d988b4d2ac568f7fd62357330b906c30a49d