logo

Marked Documentation

The parse functionparse函数

import { marked } from 'marked';
marked.parse(markdownString [,options] [,callback])
Argument论点 Type类型 Notes备注
markdownString string String of markdown source to be compiled.要编译的标记源的字符串。
options object Hash of options. 选项的散列。Can also use marked.setOptions.也可以使用marked.setOptions
callback function Called when markdownString has been parsed. 在解析完markdownString时调用。Can be used as second argument if no options present.如果不存在options,则可以用作第二个参数。

Alternative using reference替代使用参考

// Create reference instance
import { marked } from 'marked';

// Set options
// `highlight` example uses https://highlightjs.org
marked.setOptions({
  renderer: new marked.Renderer(),
  highlight: function(code, lang) {
    const hljs = require('highlight.js');
    const language = hljs.getLanguage(lang) ? lang : 'plaintext';
    return hljs.highlight(code, { language }).value;
  },
  langPrefix: 'hljs language-', // highlight.js css expects a top-level 'hljs' class.
  pedantic: false,
  gfm: true,
  breaks: false,
  sanitize: false,
  smartLists: true,
  smartypants: false,
  xhtml: false
});

// Compile
console.log(marked.parse(markdownString));

Options

Member成员 Type类型 Default默认值 Since始于 Notes备注
baseUrl string null 0.3.9 A prefix url for any relative link.任何相对链接的前缀url。
breaks boolean false v0.2.7 If true, add <br> on a single line break (copies GitHub behavior on comments, but not on rendered markdown files). Requires gfm be true.如果为true,则在单行换行符上添加<br>(复制注释上的GitHub行为,但不复制渲染的标记文件)。要求gfmtrue
gfm boolean true v0.2.1 If true, use approved GitHub Flavored Markdown (GFM) specification.如果为真,则使用经批准的GitHub 佐料Markdown(GFM)规范
headerIds boolean true v0.4.0 If true, include an id attribute when emitting headings (h1, h2, h3, etc).如果为true,则在发出标题(h1、h2、h3等)时包含id属性。
headerPrefix string '' v0.3.0 A string to prefix the id attribute when emitting headings (h1, h2, h3, etc).在发出标题(h1、h2、h3等)时作为id属性前缀的字符串。
highlight function null v0.3.0 A function to highlight code blocks, see Asynchronous highlighting.用于突出显示代码块的函数,请参阅异步突出显示
langPrefix string 'language-' v0.3.0 A string to prefix the className in a <code> block. Useful for syntax highlighting.<code>块中作为类名前缀的字符串。用于语法突出显示。
mangle boolean true v0.3.4 If true, autolinked email address is escaped with HTML character references.如果为true,自动链接的电子邮件地址将使用HTML字符引用转义。
pedantic boolean false v0.2.1 If true, conform to the original markdown.pl as much as possible. 如果为true,则尽可能多地符合markdown.plDon't fix original markdown bugs or behavior. 不要修复原始的降价错误或行为。Turns off and overrides gfm.关闭并覆盖gfm
renderer object new Renderer() v0.3.0 An object containing functions to render tokens to HTML. 包含将标记呈现为HTML的函数的对象。See extensibility for more details.有关更多详细信息,请参阅扩展性
sanitize boolean false v0.2.1 If true, sanitize the HTML passed into markdownString with the sanitizer function.如果为true,则使用sanitizer函数清理传递到markdownString中的HTML。
Warning: This feature is deprecated and it should NOT be used as it cannot be considered secure.:此功能已弃用,不应使用,因为不能将其视为安全功能。
Instead use a sanitize library, like DOMPurify (recommended), sanitize-html or insane on the output HTML!请改用一个清理库,比如DOMPurify(推荐)、sanitize-htmlinsane清理输出html!
sanitizer function null v0.3.4 A function to sanitize the HTML passed into markdownString.用于清理传递到markdownString的HTML的函数。
silent boolean false v0.2.7 If true, the parser does not throw any exception.如果为true,则解析器不会引发任何异常。
smartLists boolean false v0.2.8 If true, use smarter list behavior than those found in markdown.pl.如果为true,则使用比markdown.pl中更智能的列表行为。
smartypants boolean false v0.2.9 If true, use "smart" typographic punctuation for things like quotes and dashes.如果为真,请使用“智能”排版标点符号,如引号和破折号。
tokenizer object new Tokenizer() v1.0.0 An object containing functions to create tokens from markdown. 一个对象,包含从标记中创建标记的函数。See extensibility for more details.
walkTokens function null v1.1.0 A function which is called for every token. 为每个令牌调用的函数。See extensibility for more details.有关更多详细信息,请参阅扩展性
xhtml boolean false v0.3.2 If true, emit self-closing HTML tags for void elements (<br/>, <img/>, etc.) with a "/" as required by XHTML.如果为true,则按照XHTML的要求为空元素(<br/><img/>,等等)发出带“/”的自动关闭HTML标记。

Inline 内联Markdown

You can parse inline markdown by running markdown through marked.parseInline.您可以通过运行markdown到marked.parseInline来解析内联markdown。

const blockHtml = marked.parse('**strong** _em_');
console.log(blockHtml); // '<p><strong>strong</strong> <em>em</em></p>'

const inlineHtml = marked.parseInline('**strong** _em_');
console.log(inlineHtml); // '<strong>strong</strong> <em>em</em>'

Asynchronous highlighting异步突出显示

Unlike highlight.js the pygmentize.js library uses asynchronous highlighting. 不同于highlight.jspygmentize.js库使用异步高亮显示。This example demonstrates that marked is agnostic when it comes to the highlighter you use.这个例子表明,当你使用highlighter时,marked是不可知的。

marked.setOptions({
  highlight: function(code, lang, callback) {
    require('pygmentize-bundled') ({ lang: lang, format: 'html' }, code, function (err, result) {
      callback(err, result.toString());
    });
  }
});

marked.parse(markdownString, (err, html) => {
  console.log(html);
});

In both examples, code is a string representing the section of code to pass to the highlighter. 在这两个示例中,code都是一个字符串,表示要传递给highlighter的代码部分。In this example, lang is a string informing the highlighter what programming language to use for the code and callback is the function the asynchronous highlighter will call once complete.在本例中,lang是一个字符串,通知highlighter代码使用什么编程语言,callback是异步highlighter完成后将调用的函数。

Workers

To prevent ReDoS attacks you can run marked on a worker and terminate it when parsing takes longer than usual.为了防止重做攻击,您可以在辅助进程上运行marked,并在解析时间比平时更长时终止它。

Marked can be run in a worker thread on a node server, or a web worker in a browser.标记可以在节点服务器上的工作线程中运行,也可以在浏览器中的web工作线程中运行。

Node Worker Thread工作线程

// markedWorker.js

import { marked } from 'marked';
import { parentPort } from 'worker_threads';

parentPort.on('message', (markdownString) => {
  parentPort.postMessage(marked.parse(markdownString));
});
// index.js

import { Worker } from 'worker_threads';
const markedWorker = new Worker('./markedWorker.js');

const markedTimeout = setTimeout(() => {
  markedWorker.terminate();
  throw new Error('Marked took too long!');
}, timeoutLimit);

markedWorker.on('message', (html) => {
  clearTimeout(markedTimeout);
  console.log(html);
  markedWorker.terminate();
});

markedWorker.postMessage(markdownString);

Web Worker

NOTE: Web Workers send the payload from postMessage in an object with the payload in a .data property:Web工作线程从对象中的postMessage发送有效负载,有效负载位于.data属性中。

// markedWorker.js

importScripts('path/to/marked.min.js');

onmessage = (e) => {
  const markdownString = e.data
  postMessage(marked.parse(markdownString));
};
// script.js

const markedWorker = new Worker('./markedWorker.js');

const markedTimeout = setTimeout(() => {
  markedWorker.terminate();
  throw new Error('Marked took too long!');
}, timeoutLimit);

markedWorker.onmessage = (e) => {
  clearTimeout(markedTimeout);
  const html = e.data;
  console.log(html);
  markedWorker.terminate();
};

markedWorker.postMessage(markdownString);