# @gr2m/gray-matter 中文文档

规范地址：https://npmcn.com/package/%40gr2m/gray-matter/

版本：4\.0\.3-with-pr-137
npm 元数据更新时间：2022-04-05T15:20:50.661Z
中文译文更新时间：2026-11-16T21:23:46.334Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40gr2m/gray-matter
原文对照：https://npmcn.com/package/%40gr2m/gray-matter/?lang=original
项目主页：https://github.com/jonschlinkert/gray-matter
源码仓库：https://github.com/jonschlinkert/gray-matter

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：38.5 kB，13 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=6\.0
- 运行依赖：4 个
- 首次发布：2022-02-18T06:16:58.245Z
- 最新版本发布：2022-02-18T06:16:58.533Z
- 近 30 天下载量：15138（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：1（近 12 个月 0 个）

## 中文简介

从字符串或文件中解析前题 。 快速,可靠和易于使用. 默认情况下parses YAML前置物质,但也支持YAML,JSON,TOML或Coffee Front-Matter,并有设置自定义分隔符的选项. 用于金属匠、组装、动词和

## 安装

```sh
npm install @gr2m/gray-matter
```

也可以使用：`pnpm add @gr2m/gray-matter`、`yarn add @gr2m/gray-matter`、`bun add @gr2m/gray-matter`

## README

# 叉出那个起伏 `js-yaml` 改为v4

见 [137号](https://github.com/jonschlinkert/gray-matter/pull/137)

* * *

# 灰色物质 [![NPM version](https://img.shields.io/npm/v/gray-matter.svg?style=flat)](https://www.npmjs.com/package/gray-matter) [![NPM monthly downloads](https://img.shields.io/npm/dm/gray-matter.svg?style=flat)](https://npmjs.org/package/gray-matter) [![NPM total downloads](https://img.shields.io/npm/dt/gray-matter.svg?style=flat)](https://npmjs.org/package/gray-matter) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/gray-matter.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/gray-matter)

> 从字符串或文件中解析前题 。 快速,可靠和易于使用. 默认情况下parses YAML前置物质,但也支持YAML,JSON,TOML或Coffee Front-Matter,并有设置自定义分隔符的选项. 被金属匠,组装,动词和许多其他项目所使用.

请考虑跟随这个项目的作者, [乔恩·斯林克特](https://github.com/jonschlinkert),并考虑主演该项目以显示你的:心:和支持.

## 安装

安装方式 [无](https://www.npmjs.com/)数字 :

```sh
$ npm install --save gray-matter
```

## 抬头!

请看 [更改日志](https://npmcn.com/package/%40gr2m/gray-matter/CHANGELOG.md) 来了解在v3.0中所做的改变.

## 这有什么用?

**运行此示例**

以下示例中的 HTML 添加到 `example.html`,然后将以下代码添加到 `example.js` 运行 `$ node example` (无 `$`:

```js
const fs = require("fs");
const matter = require("gray-matter");
const str = fs.readFileSync("example.html", "utf8");
console.log(matter(str));
```

用前题转换字符串, 像这样 :

```handlebars
--- title: Hello slug: home ---
<h1>Hello world!</h1>
```

进入这样的物体:

```js
{
  content: '<h1>Hello world!</h1>',
  data: {
    title: 'Hello',
    slug: 'home'
  }
}
```

## 为什么用灰色的东西?

-   **简单**: 主函数取字符串并返回对象
-   **准确**: 优于依赖regex进行解析的前题解析器来捕捉和处理边缘案件
-   **快点**: 比其它使用正则正则解析器进行解析的前事解析器更快
-   **灵活**: 默认情况下, 灰色物质能够解析 [也门](https://github.com/nodeca/js-yaml), (中文(简体) ), [贾森](http://en.wikipedia.org/wiki/Json) 和 JavaScript 前题。 但别的地方 [发动机](https://npmcn.com/package/%40gr2m/gray-matter/#readme-optionsengines) 可添加.
-   **可扩展**: 使用 [自定义分隔符](https://npmcn.com/package/%40gr2m/gray-matter/#readme-optionsdelimiters),或添加对 [任何语言](https://npmcn.com/package/%40gr2m/gray-matter/#readme-optionsengines)一样 [移动](http://github.com/mojombo/toml), (中文(简体) ), [咖啡脚本](http://coffeescript.org/),或 [密码](https://github.com/bevry/cson)
-   **作战测试**: 由 [组装](https://github.com/assemble/assemble), (中文(简体) ), [金属匠](https://github.com/segmentio/metalsmith), (中文(简体) ), [花环](https://github.com/phenomic/phenomic), (中文(简体) ), [动词](https://github.com/assemble/verb), (中文(简体) ), [生成](https://github.com/generate/generate), (中文(简体) ), [更新](https://github.com/update/update) 还有其他许多.

**理由**

**为什么我们一开始要创造出灰色的东西?**

我们在尝试了其他不符合我们的标准和要求的图书馆之后创造了灰色的东西.

一些图书馆满足了大部分要求,但 _没有人见过他们_。 。 。 .

**这是最重要的**数字 :

-   可用,即使不简单
-   使用可靠且支持良好的库来解析 YAML
-   除YAML外支持其他语言
-   支持将字符串回YAML 或其他语言
-   内容不存在时不要失败
-   不要失败,没有前题
-   别用regex来解析. 这是一个相对简单的解析操作,而regex是最慢和最容易出错的方法.
-   直接读取 YAML 文件没有问题
-   内容复杂没有问题,包括: **非前事事项** 包含 YAML 前置物质示例的有栅栏的代码块 。 其他分析失败了.
-   支持将字符串恢复到前题 。 这对折叠,更新属性等都有用.
-   允许自定义分界器,当它是避免分界器相撞所必需的.
-   返回至少具有这三种属性的对象时:
    -   `data`:解析出 YAML 前题, 作为 JSON 对象
    -   `content`: 内容为字符串,没有前题
    -   `orig`:"原始"内容 (用于调试)

## 使用量

使用节点 `require()` 系统 :

```js
const matter = require("gray-matter");
```

或者说 [类型标记](https://www.typescriptlang.org/)

```js
import matter = require('gray-matter');
// OR
import * as matter from 'gray-matter';
```

通过字符串和 [选项](https://npmcn.com/package/%40gr2m/gray-matter/#readme-options) 改为灰色物质 :

```js
console.log(matter("---\ntitle: Front Matter\n---\nThis is content."));
```

回返情况:

```js
{
  content: '\nThis is content.',
  data: {
    title: 'Front Matter'
  }
}
```

更多关于下一节中返回的对象.

* * *

## 返回对象

灰色物质返回 a `file` 对象,其属性如下.

**可假设**

-   `file.data` **{对象}**: 通过解析前题创建的对象
-   `file.content` **{string}(string ) , \[ 弦叫 \]**: 输入字符串,与 `matter` 剥去
-   `file.excerpt` **{string}(string ) , \[ 弦叫 \]**: 节选,如果 [在选项上定义](https://npmcn.com/package/%40gr2m/gray-matter/#readme-optionsexcerpt)
-   `file.empty` **{string}(string ) , \[ 弦叫 \]**:当前题为"空"时(要么全部为白空,完全没有,要么只是评论和没有数据),原始字符串设置在这个属性上. 见 [65号](https://github.com/jonschlinkert/gray-matter/issues/65) 关于使用案例的细节.
-   `file.isEmpty` **(保罗)**: 前题为空时为真 .

**不可假定**

此外,在对象上还添加了以下非数字属性来帮助调试.

-   `file.orig` **{**: 原始输入字符串(或缓冲)
-   `file.language` **{string}(string ) , \[ 弦叫 \]**:被解析的前题语言. `yaml` 是默认
-   `file.matter` **{string}(string ) , \[ 弦叫 \]**页:1 _原始内容_未解析前事项字符串
-   `file.stringify` **{职能}**数字 : [字符串](https://npmcn.com/package/%40gr2m/gray-matter/#readme-stringify) 转换文件 `file.data` 以给定语言将字符串包入分隔符并预留到 `file.content`。 。 。 .

## 运行示例

如果你想试一下这些例子 首先克隆出灰色物质 `my-project` (或随所取地):

```sh
$ git clone https://github.com/jonschlinkert/gray-matter my-project
```

CD 进入 `my-project` 并安装依赖性 :

```sh
$ cd my-project && npm install
```

然后运行任何 [实例](https://npmcn.com/package/%40gr2m/gray-matter/examples) 以查看灰色物质如何工作:

```sh
$ node examples/<example_name>
```

**与实例的链接**

-   [咖啡业](https://npmcn.com/package/%40gr2m/gray-matter/examples/coffee.js)
-   [节选分隔符](https://npmcn.com/package/%40gr2m/gray-matter/examples/excerpt-separator.js)
-   [节选字符串](https://npmcn.com/package/%40gr2m/gray-matter/examples/excerpt-stringify.js)
-   [节选](https://npmcn.com/package/%40gr2m/gray-matter/examples/excerpt.js)
-   [日记](https://npmcn.com/package/%40gr2m/gray-matter/examples/javascript.js)
-   [json 字符串](https://npmcn.com/package/%40gr2m/gray-matter/examples/json-stringify.js)
-   [乔森](https://npmcn.com/package/%40gr2m/gray-matter/examples/json.js)
-   [恢复空](https://npmcn.com/package/%40gr2m/gray-matter/examples/restore-empty.js)
-   [节选](https://npmcn.com/package/%40gr2m/gray-matter/examples/sections-excerpt.js)
-   [节次](https://npmcn.com/package/%40gr2m/gray-matter/examples/sections.js)
-   [汤姆尔](https://npmcn.com/package/%40gr2m/gray-matter/examples/toml.js)
-   [雅姆勒字符串](https://npmcn.com/package/%40gr2m/gray-matter/examples/yaml-stringify.js)
-   [雅姆尔](https://npmcn.com/package/%40gr2m/gray-matter/examples/yaml.js)

## API 密码

### [事项](https://npmcn.com/package/%40gr2m/gray-matter/index.js#L29)

用字符串或对象 `content` 属性,从字符串中取出并解析前题,然后返回对象 `data`, (中文(简体) ), `content` 其他项目 [有用的属性](https://npmcn.com/package/%40gr2m/gray-matter/#readme-returned-object)。 。 。 .

**参数**

-   `input` **{对象}**: 字符串,或对象 `content` 字符串
-   `options` **{对象}**
-   `returns` **{对象}**

**示例**

```js
const matter = require("gray-matter");
console.log(matter("---\ntitle: Home\n---\nOther stuff"));
//=> { data: { title: 'Home'}, content: 'Other stuff' }
```

### [字符串](https://npmcn.com/package/%40gr2m/gray-matter/index.js#L160)

将对象字符串为 YAML 或指定语言, 并附加到指定字符串中 。 默认情况下,只有YAML和JSON可以被字符串. 见 [发动机](https://npmcn.com/package/%40gr2m/gray-matter/#readme-engines) 区域来学习如何将其他语言字符串化.

**参数**

-   `file` **目标**: 附加到字符串前事项的内容字符串, 或文件对象 `file.content` 绳子.
-   `data` **{对象}**: 前题需要字符串.
-   `options` **{对象}**数字 : [选项](https://npmcn.com/package/%40gr2m/gray-matter/#readme-options) 传递到灰色物质和 [日-亚姆尔](https://github.com/nodeca/js-yaml)。 。 。 .
-   `returns` **{string}(string ) , \[ 弦叫 \]**: 返回通过用分隔符将字符串相接而创建的字符串,并将它附加到给定字符串中.

**示例**

```js
console.log(matter.stringify("foo bar baz", { title: "Home" }));
// results in:
// ---
// title: Home
// ---
// foo bar baz
```

### [读取](https://npmcn.com/package/%40gr2m/gray-matter/index.js#L178)

同步读取文件系统的文件并解析前题 。 返回与 [主要函数](https://npmcn.com/package/%40gr2m/gray-matter/#readme-matter)。 。 。 .

**参数**

-   `filepath` **{string}(string ) , \[ 弦叫 \]**: 要读取的文件路径 .
-   `options` **{对象}**数字 : [选项](https://npmcn.com/package/%40gr2m/gray-matter/#readme-options) 传递到灰色的东西.
-   `returns` **{对象}**: 回归 [对象](https://npmcn.com/package/%40gr2m/gray-matter/#readme-returned-object) 与 `data` 财务报告和审定财务报表 `content`

**示例**

```js
const file = matter.read("./content/blog-post.md");
```

### [测试](https://npmcn.com/package/%40gr2m/gray-matter/index.js#L193)

如果给定返回真 `string` 有前题.

**参数**

-   `string` **{string}(string ) , \[ 弦叫 \]**
-   `options` **{对象}**
-   `returns` **(保罗)**: 如果前题存在, 则为真 .

## 选项

### 选项。节选

**类型**数字 : `Boolean|Function`

**默认**数字 : `undefined`

摘录一个直接跟随前事的节选,或者在没有前事的情况下是字符串中的第一件事.

如果设置为 `excerpt: true`它会寻找前题划界器, `---` 默认,并抓住一切导致它.

**示例**

```js
const str = "---\nfoo: bar\n---\nThis is an excerpt.\n---\nThis is content";
const file = matter(str, { excerpt: true });
```

成果:

```js
{
  content: 'This is an excerpt.\n---\nThis is content',
  data: { foo: 'bar' },
  excerpt: 'This is an excerpt.\n'
}
```

您也可以设置 `excerpt` 到一个函数。 此函数使用“ 文件” 和“ 选项” 作为参数, 以控制从内容中提取节选 .

**示例**

```js
// returns the first 4 lines of the contents
function firstFourLines(file, options) {
  file.excerpt = file.content.split("\n").slice(0, 4).join(" ");
}

const file = matter(
  [
    "---",
    "foo: bar",
    "---",
    "Only this",
    "will be",
    "in the",
    "excerpt",
    "but not this...",
  ].join("\n"),
  { excerpt: firstFourLines }
);
```

成果:

```js
{
  content: 'Only this\nwill be\nin the\nexcerpt\nbut not this...',
  data: { foo: 'bar' },
  excerpt: 'Only this will be in the excerpt'
}
```

### 选项.节选 分隔符

**类型**数字 : `String`

**默认**数字 : `undefined`

定义用于节选的自定义分隔符 .

```js
console.log(matter(string, { excerpt_separator: "<!-- end -->" }));
```

**示例**

以下 HTML 字符串 :

```html
---
title: Blog
---

My awesome blog.
<!-- end -->
<h1>Hello world</h1>
```

成果:

```js
{
  data: { title: 'Blog'},
  excerpt: 'My awesome blog.',
  content: 'My awesome blog.\n<!-- end -->\n<h1>Hello world</h1>'
}
```

### 选项

定义用于解析和/或字符串前题的自定义引擎 .

**类型**数字 : `Object` 发动机对象

**默认**数字 : `JSON`, (中文(简体) ), `YAML` 财务报告和审定财务报表 `JavaScript` 默认已处理.

**引擎格式**

发动机可以是具有下列特性的物体: `parse` 和(可选) `stringify` 方法,或仅用于解析的函数.

**实例**

```js
const toml = require("toml");

/**
 * defined as a function
 */

const file = matter(str, {
  engines: {
    toml: toml.parse.bind(toml),
  },
});

/**
 * Or as an object
 */

const file = matter(str, {
  engines: {
    toml: {
      parse: toml.parse.bind(toml),

      // example of throwing an error to let users know stringifying is
      // not supported (a TOML stringifier might exist, this is just an example)
      stringify: function () {
        throw new Error("cannot stringify to TOML");
      },
    },
  },
});

console.log(file);
```

### 选项。语言

**类型**数字 : `String`

**默认**数字 : `yaml`

定义用于解析前题的引擎 .

```js
console.log(matter(string, { language: "toml" }));
```

**示例**

以下 HTML 字符串 :

```html
---
title = "TOML"
description = "Front matter"
categories = "front matter toml"
---

This is content
```

成果:

```js
{ content: 'This is content',
  excerpt: '',
  data:
   { title: 'TOML',
     description: 'Front matter',
     categories: 'front matter toml' } }
```

**动态语言检测**

灰色物质不会定义选项上的语言,而是会自动检测第一个分隔符后定义的语言并选择用于解析的正确引擎.

```html
---toml
title = "TOML"
description = "Front matter"
categories = "front matter toml"
---

This is content
```

### 选项。界限

**类型**数字 : `String`

**默认**数字 : `---`

打开和关闭的分隔符可以作为字符串的数组传递.

**示例**

```js
// format delims as a string
matter.read("file.md", { delims: "~~~" });
// or an array (open/close)
matter.read("file.md", { delims: ["~~~", "~~~"] });
```

将解析:

```html
~~~ title: Home ~~~ This is the {{title}} page.
```

## 折旧选项

### 选项。lang

减号,请使用 [选项。语言](https://npmcn.com/package/%40gr2m/gray-matter/#readme-optionslanguage) 换句话说.

### 选项.delims

减号,请使用 [选项。界限](https://npmcn.com/package/%40gr2m/gray-matter/#readme-optionsdelimiters) 换句话说.

### 选项。参数

减号,请使用 [选项](https://npmcn.com/package/%40gr2m/gray-matter/#readme-optionsengines) 换句话说.

## 关于

**捐款**

拉出请求和星星总是受欢迎的. 对于错误和特性请求, [请创建一个问题](https://npmcn.com/package/issues/new)。 。 。 .

**运行测试**

运行和审查单元测试是熟悉图书馆及其API的好办法。 您可以使用以下命令安装依赖性并运行测试:

```sh
$ npm install && npm test
```
**大楼文件**

_(此工程的 readme.md 由 [动词](https://github.com/verbose/verb-generate-readme)请不要直接编辑读取器。 读取器的任何改动必须在 [动词 md](https://npmcn.com/package/%40gr2m/gray-matter/.verb.md) 读取我的模板。 )_

要生成读取, 请运行以下命令 :

```sh
$ npm install -g verbose/verb#dev verb-generate-readme && verb
```

### 相关项目

您可能也对这些项目感兴趣:

-   [组装](https://www.npmjs.com/package/assemble)把石头从袜子上取出来! 集合让您快速创建网络项目.. [更多](https://github.com/assemble/assemble) | [主页](https://github.com/assemble/assemble "Get the rocks out of your socks! Assemble makes you fast at creating web projects. Assemble is used by thousands of projects for rapid prototyping, creating themes, scaffolds, boilerplates, e-books, UI components, API documentation, blogs, building websit")
-   [金属匠](https://www.npmjs.com/package/metalsmith): 一个极其简单,可接通的静态站点生成器. QQ [主页](https://github.com/segmentio/metalsmith#readme "An extremely simple, pluggable static site generator.")
-   [动词](https://www.npmjs.com/package/verb): GitHub 项目的文档生成器。 动词力极强,易于使用,并被使用 [更多](https://github.com/verbose/verb) | [主页](https://github.com/verbose/verb "Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used on hundreds of projects of all sizes to generate everything from API docs to readmes.")
-   [灰色物质装载器](https://github.com/atlassian/gray-matter-loader):一个灰色物品的网包装载器. [主页](https://github.com/atlassian/gray-matter-loader#gray-matter-loader)

### 贡献者

| **提交** | **贡献者** |
| --- | --- |
| 174国道 | [扬施林克特](https://github.com/jonschlinkert) |
| 第7条 | [罗布洛克](https://github.com/RobLoach) |
| 页:1 | [{\\fn黑体\\fs22\\bord1\\shad0\\3ahbe\\4ah00\\fscx67\\fscy66\\2chffffff\\3ch808080}嘿 哥们](https://github.com/heymind) |
| 页:1 | [鸽子](https://github.com/doowb) |
| 3个 | [极乐世界](https://github.com/aljopro) |
| 2个 | [矩形](https://github.com/reccanti) |
| 2个 | [顶点](https://github.com/onokumus) |
| 2个 | [moo克语name](https://github.com/moozzyk) |
| 1个 | [阿杰迪32号](https://github.com/Ajedi32) |
| 1个 | [开萨](https://github.com/caesar) |
| 1个 | [扬·斯通克勒](https://github.com/ianstormtaylor) |
| 1个 | [克立方米](https://github.com/qm3ster) |
| 1个 | [扎克瓦利语name](https://github.com/zachwhaley) |

### 作者

**乔恩·斯林克特**

-   [链接到配置文件](https://linkedin.com/in/jonschlinkert)
-   [GitHub 配置文件](https://github.com/jonschlinkert)
-   [推特简介](https://twitter.com/jonschlinkert)

### 许可证

版权: 2018, [乔恩·斯林克特](https://github.com/jonschlinkert)。 。 。 . 释放 [MIT 许可证](https://npmcn.com/package/%40gr2m/gray-matter/LICENSE)。 。 。 .

* * *

_此文件由 [动词基因读取器](https://github.com/verbose/verb-generate-readme),v 6.0,于2018年4月01日查阅._

## 常见问题

### @gr2m/gray-matter 是什么？

从字符串或文件中解析前题 。 快速,可靠和易于使用\. 默认情况下parses YAML前置物质,但也支持YAML,JSON,TOML或Coffee Front-Matter,并有设置自定义分隔符的选项\. 用于金属匠、组装、动词和

### 如何安装 @gr2m/gray-matter？

在项目目录运行 npm install @gr2m/gray-matter，或使用 pnpm add / yarn add / bun add。

### @gr2m/gray-matter 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @gr2m/gray-matter 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @gr2m/gray-matter 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=6\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @gr2m/gray-matter 可以商用吗？

@gr2m/gray-matter 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @gr2m/gray-matter 的下载量有多少？

根据 npm 官方下载统计，@gr2m/gray-matter 在 2026/10/17 – 2026/11/15 这 30 天内被下载 15,138 次，日均约 505 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @gr2m/gray-matter 还在维护吗？

最新版本 4\.0\.3-with-pr-137 发布于 2022/02/18（4 年前）；至今共发布 1 个版本，其中过去 12 个月发布了 0 个；首次发布于 2022/02/18。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

