gray-matter中文文档|gray-matter js中文教程|解析

npm npmdoc 3年前 (2021-10-30) 1957次浏览

gray-matter中文文档|gray-matter js中文教程|解析

安装命令:npm i gray-matter

灰质 NPM 版本 NPM 每月下载量 NPM 总下载量 Linux 构建状态

从字符串或文件中解析前面的内容。快速、可靠且易于使用。默认情况下解析 YAML 前端,但也支持 YAML、JSON、TOML 或 Coffee Front-Matter,并提供设置自定义分隔符的选项。被金属匠、组装、动词和许多其他项目使用。

请考虑关注该项目的作者Jon Schlinkert,并考虑为该项目加星以展示您的❤️ 和支持。

安装

使用npm安装

$ npm install --save gray-matter

当心!

请查看更改日志以了解在 v3.0 中所做的重大更改。

这有什么作用?

运行这个例子

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

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

转换一个带有前置内容的字符串,如下所示:

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

变成这样的对象:

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

为什么要使用灰质?

  • simple : main 函数接受一个字符串并返回一个对象
  • 准确:比依赖正则表达式进行解析的前端解析器更擅长捕捉和处理边缘情况
  • fast:比其他使用正则表达式进行解析的前端解析器更快
  • 灵活:默认情况下,gray-matter 能够解析YAMLJSON和 JavaScript 前端。但是可以添加其他引擎
  • 可扩展:使用自定义分隔符,或添加对任何语言的支持,如TOMLCoffeeScriptCSON
  • 实战检验:通过使用装配metalsmithphenomic动词生成更新和其他许多人。
基本原理

为什么我们首先要创造灰质?

在尝试了其他不符合我们标准和要求的库后,我们创建了灰质。

Some libraries met most of the requirements, but none met all of them.

Here are the most important:

  • Be usable, if not simple
  • Use a dependable and well-supported library for parsing YAML
  • Support other languages besides YAML
  • Support stringifying back to YAML or another language
  • Don’t fail when no content exists
  • Don’t fail when no front matter exists
  • Don’t use regex for parsing. This is a relatively simple parsing operation, and regex is the slowest and most error-prone way to do it.
  • Have no problem reading YAML files directly
  • Have no problem with complex content, including non-front-matter fenced code blocks that contain examples of YAML front matter. Other parsers fail on this.
  • 支持字符串化回到前面。这对于 linting、更新属性等很有用。
  • 当需要避免分隔符冲突时,允许自定义分隔符。
  • 应该返回一个至少具有以下三个属性的对象:

    • data:解析的 YAML 前端,作为 JSON 对象
    • content: 内容为字符串,没有前面的内容
    • orig:“原始”内容(用于调试)

用法

使用 Node 的require()系统:

const matter = require('gray-matter');

或者用打字稿

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

将字符串和选项传递给灰质:

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

返回:

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

在下一节中详细了解返回的对象。


返回对象

灰质返回file具有以下属性对象。

可枚举

  • file.data {Object} : 解析 front-matter 创建的对象
  • file.content {String} : 输入字符串,matter去掉
  • file.excerpt {String}:摘录,如果在选项上定义
  • file.empty {String}:当前面的内容为“空”(全是空格,什么都没有,或者只是注释而没有数据)时,在此属性上设置原始字符串。有关用例的详细信息,请参阅#65
  • file.isEmpty {Boolean} : true 如果 front-matter 为空。

不可枚举

此外,还向对象添加了以下不可编号的属性以帮助调试。

  • file.orig {Buffer}:原始输入字符串(或缓冲区)
  • file.language {String}:被解析的前端语言。yaml是默认值
  • file.matter {String} :未解析原始字符串
  • file.stringify {}功能字符串化的转换文件file.data为一个字符串在给定的语言,分隔符包装它,它前面加来file.content

运行示例

如果你想试驾这些例子,首先将灰质克隆到my-project(或你想要的任何地方):

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

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

$ cd my-project && npm install

然后运行任何示例以查看灰质是如何工作的:

$ node examples/<example_name>

示例链接

应用程序接口

事情

以一个字符串或对象与content来自字符串属性,提取物和解析前物质,然后返回与对象datacontent和其他有用的性质

参数

  • input {Object|String} : 字符串,或带有content字符串的对象
  • options {目的}
  • returns {目的}

例子

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

.stringify

将对象字符串化为 YAML 或指定的语言,并将其附加到给定的字符串。默认情况下,只能对 YAML 和 JSON 进行字符串化。请参阅引擎部分以了解如何对其他语言进行字符串化。

参数

  • file {String|Object}:要附加到字符串化的前端的内容字符串,或带有file.content字符串的文件对象
  • data {Object}:要字符串化的前件。
  • options {对象}选项传递给灰质和JS-YAML
  • returns {String}:返回通过用分隔符包装字符串化的 yaml 并将其附加到给定字符串而创建的字符串。

例子

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

。读

从文件系统同步读取文件并解析前端。返回与主函数相同的对象

参数

  • filepath {String} : 要读取的文件的文件路径。
  • options {Object}传递给灰质的选项
  • returns {Object} : 返回一个带有data的对象content

例子

const file = matter.read('./content/blog-post.md');

。测试

如果给定的string有前置问题,则返回 true

参数

  • string {细绳}
  • options {目的}
  • returns {Boolean} : 如果前面的内容存在,则为真。

选项

选项.摘录

类型:Boolean|Function

默认undefined

提取直接跟在前面的摘录,或者如果不存在前面的内容则是字符串中的第一件事。

如果设置为excerpt: true,则---默认情况下,它将查找 frontmatter 分隔符并获取通向它的所有内容。

例子

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

结果是:

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

您也可以设置excerpt为一个功能。此函数使用最初作为参数传递给灰质的“文件”和“选项”,因此您可以控制如何从内容中提取摘录。

例子

// 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});

结果是:

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

options.excerpt_separator

类型:String

默认undefined

定义用于摘录的自定义分隔符。

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

例子

以下 HTML 字符串:

---
title: Blog
---
My awesome blog.
<!-- end -->
<h1>Hello world</h1>

结果是:

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

options.engines

定义用于解析和/或字符串化前沿问题的自定义引擎。

类型Object引擎对象

默认: JSONYAML并且JavaScript已经默认处理。

引擎格式

引擎可以是具有parse和(可选)stringify方法的对象,也可以是仅用于解析的函数。

例子

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

定义用于解析前端的引擎。

console.log(matter(string, {language: 'toml'}));

例子

以下 HTML 字符串:

---
title = "TOML"
description = "Front matter"
categories = "front matter toml"
---
This is content

结果是:

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

动态语言检测

不是在选项上定义语言,gray-matter 将自动检测第一个分隔符后定义的语言,并选择正确的引擎进行解析。

---toml
title = "TOML"
description = "Front matter"
categories = "front matter toml"
---
This is content

options.delimiters

类型:String

默认---

打开和关闭定界符可以作为字符串数组传入。

例子:

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

会解析:

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

已弃用的选项

选项.lang

已弃用,请改用options.language

options.delims

已弃用,请改用options.delimiters

options.parsers

已弃用,请改用options.engines

关于

贡献

拉取请求和星星总是受欢迎的。对于错误和功能请求,请创建问题

运行测试

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

$ npm install && npm test
构建文档

(本项目的 readme.md 是由verb生成的,请不要直接编辑 readme。对 readme 的任何更改都必须在.verb.md readme 模板中进行。)

要生成自述文件,请运行以下命令:

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

相关项目

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

贡献者

提交 贡献者
174 琼施林克特
7 罗布洛奇
5 嘿嘿嘿
4 豆豆
3 阿乔普罗
2 雷坎蒂
2 鬼怪
2 穆兹克
1 阿杰迪32
1 凯撒
1 伊恩斯托斯特泰勒
1 qm3ster
1 扎克威利

作者

乔恩·施林克特

执照

版权所有 © 2018,乔恩·施林克特MIT 许可发布


此文件由verb-generate-readme v0.6.0 于2018 年4 月1 日生成

项目贡献人员列表:


极客公园 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:gray-matter中文文档|gray-matter js中文教程|解析
喜欢 (0)
.excerpt .focus {display:none}