Home

Awesome

gray-matter NPM version NPM monthly downloads NPM total downloads

Parse front-matter from a string or file. Fast, reliable and easy to use. Parses YAML front matter by default, but also has support for YAML, JSON, TOML or Coffee Front-Matter, with options to set custom delimiters. Used by metalsmith, assemble, verb and many other projects.

Please consider following this project's author, Jon Schlinkert, and consider starring the project to show your :heart: and support.

Install

Install with npm:

$ npm install --save gray-matter

Heads up!

Please see the changelog to learn about breaking changes that were made in v3.0.

<br />

Sponsors

Thanks to the following companies, organizations, and individuals for supporting the ongoing maintenance and development of gray-matter! Become a Sponsor to add your logo to this README, or any of my other projects

Gold Sponsors

<img src="https://github.com/jonschlinkert/gray-matter/assets/383994/12afc199-d1c3-450b-a75d-c5456c8201dc" alt="https://jaake.tech/" width="100"/>
https://jaake.tech/
<br />

What does this do?

<details> <summary><strong>Run this example</strong></summary>

Add the HTML in the following example to example.html, then add the following code to example.js and run $ node example (without the $):

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

Converts a string with front-matter, like this:

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

Into an object like this:

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

Why use gray-matter?

<details> <summary><strong>Rationale</strong></summary>

Why did we create gray-matter in the first place?

We created gray-matter after trying out other libraries that failed to meet our standards and requirements.

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

Here are the most important:

</details>

Usage

Using Node's require() system:

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

Or with typescript

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

Pass a string and options to gray-matter:

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

Returns:

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

More about the returned object in the following section.


Returned object

gray-matter returns a file object with the following properties.

Enumerable

Non-enumerable

In addition, the following non-enumberable properties are added to the object to help with debugging.

Run the examples

If you'd like to test-drive the examples, first clone gray-matter into my-project (or wherever you want):

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

CD into my-project and install dependencies:

$ cd my-project && npm install

Then run any of the examples to see how gray-matter works:

$ node examples/<example_name>

Links to examples

API

matter

Takes a string or object with content property, extracts and parses front-matter from the string, then returns an object with data, content and other useful properties.

Params

Example

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

.stringify

Stringify an object to YAML or the specified language, and append it to the given string. By default, only YAML and JSON can be stringified. See the engines section to learn how to stringify other languages.

Params

Example

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

.read

Synchronously read a file from the file system and parse front matter. Returns the same object as the main function.

Params

Example

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

.test

Returns true if the given string has front matter.

Params

Options

options.excerpt

Type: Boolean|Function

Default: undefined

Extract an excerpt that directly follows front-matter, or is the first thing in the string if no front-matter exists.

If set to excerpt: true, it will look for the frontmatter delimiter, --- by default and grab everything leading up to it.

Example

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

Results in:

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

You can also set excerpt to a function. This function uses the 'file' and 'options' that were initially passed to gray-matter as parameters, so you can control how the excerpt is extracted from the content.

Example

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

Results in:

{
  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

Type: String

Default: undefined

Define a custom separator to use for excerpts.

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

Example

The following HTML string:

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

Results in:

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

options.engines

Define custom engines for parsing and/or stringifying front-matter.

Type: Object Object of engines

Default: JSON, YAML and JavaScript are already handled by default.

Engine format

Engines may either be an object with parse and (optionally) stringify methods, or a function that will be used for parsing only.

Examples

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

options.language

Type: String

Default: yaml

Define the engine to use for parsing front-matter.

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

Example

The following HTML string:

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

Results in:

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

Dynamic language detection

Instead of defining the language on the options, gray-matter will automatically detect the language defined after the first delimiter and select the correct engine to use for parsing.

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

options.delimiters

Type: String

Default: ---

Open and close delimiters can be passed in as an array of strings.

Example:

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

would parse:

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

Deprecated options

options.lang

Decrecated, please use options.language instead.

options.delims

Decrecated, please use options.delimiters instead.

options.parsers

Decrecated, please use options.engines instead.

About

<details> <summary><strong>Contributing</strong></summary>

Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.

</details> <details> <summary><strong>Running Tests</strong></summary>

Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:

$ npm install && npm test
</details> <details> <summary><strong>Building docs</strong></summary>

(This project's readme.md is generated by verb, please don't edit the readme directly. Any changes to the readme must be made in the .verb.md readme template.)

To generate the readme, run the following command:

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

Related projects

You might also be interested in these projects:

Contributors

CommitsContributor
179jonschlinkert
13robertmassaioli
7RobLoach
5doowb
5heymind
3aljopro
3shawnbot
2reccanti
2onokumus
2moozzyk
2ajaymathur
1Ajedi32
1arlair
1caesar
1ianstormtaylor
1qm3ster
1zachwhaley

Author

Jon Schlinkert

License

Copyright © 2023, Jon Schlinkert. Released under the MIT License.


This file was generated by verb-generate-readme, v0.8.0, on July 12, 2023.