• Stars
    star
    3,863
  • Rank 11,358 (Top 0.3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 11 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Smarter YAML front matter parser, used by metalsmith, Gatsby, Netlify, Assemble, mapbox-gl, phenomic, vuejs vitepress, TinaCMS, Shopify Polaris, Ant Design, Astro, hashicorp, garden, slidev, saber, sourcegraph, and many others. Simple to use, and battle tested. Parses YAML by default but can also parse JSON Front Matter, Coffee Front Matter, TOML Front Matter, and has support for custom parsers. Please follow gray-matter's author: https://github.com/jonschlinkert

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 ❀️ 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.


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

https://jaake.tech/
https://jaake.tech/

What does this do?

Run this example

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

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?

  • simple: main function takes a string and returns an object
  • accurate: better at catching and handling edge cases than front-matter parsers that rely on regex for parsing
  • fast: faster than other front-matter parsers that use regex for parsing
  • flexible: By default, gray-matter is capable of parsing YAML, JSON and JavaScript front-matter. But other engines may be added.
  • extensible: Use custom delimiters, or add support for any language, like TOML, CoffeeScript, or CSON
  • battle-tested: used by assemble, metalsmith, phenomic, verb, generate, update and many others.
Rationale

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:

  • 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.
  • Support stringifying back to front-matter. This is useful for linting, updating properties, etc.
  • Allow custom delimiters, when it's necessary for avoiding delimiter collision.
  • Should return an object with at least these three properties:
    • data: the parsed YAML front matter, as a JSON object
    • content: the contents as a string, without the front matter
    • orig: the "original" content (for debugging)

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

  • file.data {Object}: the object created by parsing front-matter
  • file.content {String}: the input string, with matter stripped
  • file.excerpt {String}: an excerpt, if defined on the options
  • file.empty {String}: when the front-matter is "empty" (either all whitespace, nothing at all, or just comments and no data), the original string is set on this property. See #65 for details regarding use case.
  • file.isEmpty {Boolean}: true if front-matter is empty.

Non-enumerable

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

  • file.orig {Buffer}: the original input string (or buffer)
  • file.language {String}: the front-matter language that was parsed. yaml is the default
  • file.matter {String}: the raw, un-parsed front-matter string
  • file.stringify {Function}: stringify the file by converting file.data to a string in the given language, wrapping it in delimiters and prepending it to file.content.

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

  • input {Object|String}: String, or object with content string
  • options {Object}
  • returns {Object}

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

  • file {String|Object}: The content string to append to stringified front-matter, or a file object with file.content string.
  • data {Object}: Front matter to stringify.
  • options {Object}: Options to pass to gray-matter and js-yaml.
  • returns {String}: Returns a string created by wrapping stringified yaml with delimiters, and appending that to the given string.

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

  • filepath {String}: file path of the file to read.
  • options {Object}: Options to pass to gray-matter.
  • returns {Object}: Returns an object with data and content

Example

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

.test

Returns true if the given string has front matter.

Params

  • string {String}
  • options {Object}
  • returns {Boolean}: True if front matter exists.

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

Contributing

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

Running Tests

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
Building docs

(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

Related projects

You might also be interested in these projects:

  • assemble: Get the rocks out of your socks! Assemble makes you fast at creating web projects… more | homepage
  • metalsmith: An extremely simple, pluggable static site generator. | homepage
  • verb: Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used… more | homepage

Contributors

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

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.

More Repositories

1

remarkable

Markdown parser, done right. Commonmark support, extensions, syntax plugins, high speed - all in one. Gulp and metalsmith plugins available. Used by Facebook, Docusaurus and many others! Use https://github.com/breakdance/breakdance for HTML-to-markdown conversion. Use https://github.com/jonschlinkert/markdown-toc to generate a table of contents.
JavaScript
5,745
star
2

markdown-toc

API and CLI for generating a markdown TOC (table of contents) for a README or any markdown files. Uses Remarkable to parse markdown. Used by NASA/openmct, Prisma, Joi, Mocha, Sass, Prettier, Orbit DB, FormatJS, Raneto, hapijs/code, webpack-flow, docusaurus, release-it, ts-loader, json-server, reactfire, bunyan, husky, react-easy-state, react-snap, chakra-ui, carbon, alfresco, repolinter, Assemble, Verb, and thousands of other projects.
JavaScript
1,508
star
3

gulp-htmlmin

Minify HTML
HTML
730
star
4

sublime-markdown-extended

Top 100 Sublime Text plugin! Markdown syntax highlighter for Sublime Text, with extended support for GFM fenced code blocks, with language-specific syntax highlighting. YAML Front Matter. Works with ST2/ST3. Goes great with Assemble.
658
star
5

maintainers-guide-to-staying-positive

Don't let the trolls get you down! Use this as a reference to avoid open-source burnout and keep doing what you love: writing code! Contributions and any kind of improvements are very welcome!
625
star
6

sublime-monokai-extended

Extends Monokai from Soda with additional syntax highlighting for Markdown, LESS, HTML, Handlebars and more.
511
star
7

kind-of

Get the native JavaScript type of a value, fast. Used by superstruct, micromatch and many others!
JavaScript
334
star
8

clone-deep

Recursively (deep) clone JavaScript native types, like Object, Array, RegExp, Date as well as primitives. Used by superstruct, merge-deep, and many others!
JavaScript
305
star
9

set-value

Set nested properties on an object using dot-notation.
JavaScript
261
star
10

is-number

JavaScript/Node.js utility. Returns `true` if the value is a number or string number. Useful for checking regex match results, user input, parsed strings, etc.
JavaScript
256
star
11

get-value

Use property paths (`a.b.c`) get a nested value from an object.
JavaScript
229
star
12

word-wrap

Wrap words to a specified length.
JavaScript
194
star
13

randomatic

Easily generate random strings like passwords, with simple options for specifying a length and for using patterns of numeric, alpha-numeric, alphabetical, special or custom characters. (the original "generate-password")
JavaScript
178
star
14

data-store

Easily get, set and persist config data. Fast. Supports dot-notation in keys. No dependencies.
JavaScript
158
star
15

is-plain-object

Returns true if the given value is an object created by the Object constructor.
HTML
147
star
16

guide-to-staying-productive

If you're looking for ways to stay motivated and focused, while still having fun, this guide is for you! Contributions and any kind of improvements are very welcome!
136
star
17

pretty

Sensible presets and some tweaks for beautifying HTML with js-beautify according to my preferences.
JavaScript
135
star
18

parse-github-url

Parse a Github URL into an object. Supports a wide variety of GitHub URL formats.
JavaScript
117
star
19

time-stamp

Get a formatted timestamp. Used in gulp, assemble, generate, and many others.
JavaScript
112
star
20

idiomatic-contributing

A brief guide to being an effective open source contributor.
111
star
21

merge-deep

Recursively merge values in a JavaScript object.
JavaScript
111
star
22

strip-comments

Strip block comments or line comments from JavaScript code.
JavaScript
105
star
23

isobject

Is the value an object, and not an array or null?
JavaScript
101
star
24

normalize-path

Normalize file path slashes to be unix-like forward slashes. Used by chokidar, anymatch, and many others!
JavaScript
99
star
25

gists

Methods for working with the GitHub Gist API. Node.js/JavaScript
JavaScript
97
star
26

copy

Copy files using glob patterns. Sync, async, promise or streams. (node.js utility)
JavaScript
93
star
27

git-branch

Get the current branch for a local git repository
JavaScript
91
star
28

dashify

Convert a string to a dash-separated string (kebab case). Works with camelcase, pascalcase, space-separated, etc.
JavaScript
86
star
29

vertical-rhythm

Put some typographical vertical rhythm in your CSS. LESS, Stylus and SCSS/SASS versions included.
CSS
85
star
30

write

Write data to the file system, creating any intermediate directories if they don't already exist. Used by flat-cache and many others!
JavaScript
82
star
31

window-size

Reliable way to to get the height and width of the terminal/console in a node.js environment.
JavaScript
80
star
32

object.omit

Return a copy of an object without the given keys.
JavaScript
79
star
33

mixin-deep

Deeply mix the properties of objects into the first object, while also mixing-in child objects.
JavaScript
79
star
34

assign-deep

Deeply assign the enumerable properties of source objects to a destination object.
JavaScript
78
star
35

grunt-prettify

Grunt plugin for beautifying HTML. Lots of options so that you can format/beautify the generated HTML the way you want it.
JavaScript
77
star
36

template-helpers

Generic JavaScript helpers that can be used with any template engine. Handlebars, Lo-Dash, Underscore, or any engine that supports helper functions.
JavaScript
75
star
37

omit-deep

Recursively omit specified keys from an object.
JavaScript
73
star
38

omit-empty

Recursively omit empty properties from an object. Omits empty objects, arrays, strings, and optionally zero. Similar results to what you would expect with `compact` for arrays.
JavaScript
73
star
39

array-sort

Fast and powerful array sorting. Sort an array of objects by one or more properties. Any number of nested properties or custom comparison functions may be used.
JavaScript
72
star
40

dry

Dry is a new template engine and language, and is a superset of Shopify's Liquid, with first-class support for advanced inheritance features, and more. From the creators of Enquirer, Assemble, Remarkable, and Micromatch.
JavaScript
69
star
41

grunt-refactor

Grunt tasks for re-factoring code.
JavaScript
65
star
42

parse-comments

Parse JavaScript code comments. Works with block and line comments, and should work with CSS, LESS, SASS, or any language with the same comment formats.
JavaScript
64
star
43

utils

Fast, generic JavaScript/node.js utility functions.
JavaScript
61
star
44

github-base

Simple, opinionated node.js interface for creating basic apps with the GitHub API.
JavaScript
60
star
45

arr-flatten

Recursively flatten an array or arrays. This is the fastest implementation of array flatten.
JavaScript
60
star
46

templates

System for creating and managing view collections, rendering, engines, routes and more. See the "dev" branch for most recent updates.
JavaScript
60
star
47

parse-gitignore

Parse a gitignore file into an array of patterns. Comments and empty lines are stripped.
JavaScript
59
star
48

parse-git-config

Parse `.git/config` into a JavaScript object. sync or async.
JavaScript
58
star
49

array-unique

Return an array free of duplicate values. Very fast implementation.
JavaScript
58
star
50

sublime-swig

Swig template syntax highlighting for Sublime Text.
58
star
51

to-regex

Generate a regex from a string or array of strings.
JavaScript
56
star
52

split-string

Split a string on a given character or characters, with support for escaping.
JavaScript
55
star
53

fill-range

Fill in a range of numbers or letters, positive or negative, optionally passing an increment or multiplier to use.
JavaScript
54
star
54

cache-base

Basic object store with methods like get/set/extend/omit
JavaScript
54
star
55

template

Render templates from any engine. Make custom template types, use layouts on pages, partials or any custom template type, custom delimiters, helpers, middleware, routes, loaders, and lots more. Powers Assemble v0.6.0, Verb v0.3.0 and your application.
JavaScript
54
star
56

align-text

Align the text in a string.
JavaScript
51
star
57

grunt-fixmyjs

Automatically fix js-hint errors.
JavaScript
51
star
58

lazy-cache

Cache requires to be lazy-loaded when needed. Uses node's own require system with tried and true, plain-vanilla JavaScript getters.
JavaScript
51
star
59

gulp-prettify

Prettify HTML.
HTML
50
star
60

exponential-moving-average

Calculate an exponential moving average from an array of numbers.
JavaScript
50
star
61

pretty-time

Easily format the time from node.js `process.hrtime`. Works with timescales ranging from weeks to nanoseconds.
JavaScript
50
star
62

is-windows

Returns true if the platform is Windows (and Cygwin or MSYS/MinGW for unit tests)
JavaScript
48
star
63

extract-comments

Extract JavaScript code comments from a string or glob of files.
JavaScript
46
star
64

repeat-string

Repeat the given string n times. Fastest implementation for repeating a string (2x faster than the native method)
JavaScript
45
star
65

arr-diff

Returns an array with only the unique values from all given arrays using strict equality for comparisons.
JavaScript
44
star
66

pad-left

Left pad a string with zeros or a specified string. Fastest implementation.
JavaScript
44
star
67

unixify

Convert a windows file path to a unix-style file path.
JavaScript
42
star
68

object.pick

(object pick) returns a filtered copy of an object with only the specified keys, exactly like `pick` from lo-dash / underscore.
JavaScript
42
star
69

delete-empty

Recursively delete all empty folders in a directory and child directories.
JavaScript
41
star
70

handlebars-delimiters

Custom delimiters, for Handlebars templates.
JavaScript
41
star
71

write-yaml

Basic node.js utility for converting JSON to YAML and writing formatting YAML files to disk.
JavaScript
40
star
72

regex-cache

Memoize the results of a call to the RegExp constructor, avoiding repetitious runtime compilation of the same string and options, resulting in dramatic speed improvements.
JavaScript
39
star
73

unescape

Convert HTML entities to HTML characters, e.g. `&gt;` => `>`.
JavaScript
38
star
74

pascalcase

Convert a string to pascal case (upper camel case). Used by more than 8.7 million projects on GitHub! Please follow this library's author: https://github.com/jonschlinkert
JavaScript
36
star
75

is-primitive

Is the typeof value a javascript primitive?
JavaScript
36
star
76

is-git-url

Regex to validate that a URL is a git URL.
JavaScript
35
star
77

deep-rename-keys

Recursively rename the keys in an object.
JavaScript
35
star
78

unset-value

Delete nested properties from an object using dot notation.
JavaScript
34
star
79

fs-utils

Generalized file and path utils for Node.js projects.
JavaScript
34
star
80

array-last

Return the last element in an array. Faster than `.slice`
JavaScript
34
star
81

relative

Easily calculate the relative path from file A to file B in Node.js project. Will calculate correctly from a file to a directory, file to file, directory to file, and directory to directory.
JavaScript
34
star
82

for-in

Iterate over the enumerable properties of an object, and return an object with properties that evaluate to true from the callback. Exit early by returning `false`.
JavaScript
33
star
83

global-modules

Returns the directory used by NPM for globally installed NPM packages.
JavaScript
33
star
84

extend-shallow

Extend object A with the properties of object B. node.js/javascript util.
JavaScript
32
star
85

eval-estree-expression

Safely evaluate JavaScript (estree) expressions, sync and async.
JavaScript
32
star
86

regex-not

Create a javascript regular expression for matching everything except for the given string.
JavaScript
31
star
87

longest

Get the length of the longest item in an array.
JavaScript
31
star
88

whence

Add context awareness to your apps and frameworks by safely evaluating user-defined conditional expressions. Useful for evaluating expressions in config files, prompts, key bindings, completions, templates, and many other user cases.
JavaScript
31
star
89

markdown-utils

Convert plain text into snippets of markdown.
JavaScript
30
star
90

grunt-readme

DEPRECATED. Use Verb instead
JavaScript
30
star
91

js-comments

Parse JavaScript code comments and generate API documentation.
JavaScript
30
star
92

justified

Wrap, align and justify the words in a string.
JavaScript
29
star
93

is-equal-shallow

Does a shallow comparison of two objects, returning false if the keys or values differ.
JavaScript
29
star
94

shallow-clone

Make a shallow clone of an object, array or primitive.
JavaScript
29
star
95

parse-filepath

Parse a filepath and return an object of path parts. Falls back on native node.js `path.parse` if it exists
JavaScript
29
star
96

yarn-api

Basic API for yarn.
JavaScript
28
star
97

is-directory

Extends `stats.isDirectory()`, returns `true` if a filepath is a directory.
JavaScript
28
star
98

global-prefix

Get the npm global path prefix. Same code used internally by npm.
JavaScript
28
star
99

rename-keys

Modify/rename the keys of the own enumerable properties of an object.
JavaScript
27
star
100

has-value

Returns true if a value exists, false if empty. Works with deeply nested values using object paths.
JavaScript
27
star