{"id":13458972,"url":"https://github.com/jonschlinkert/gray-matter","last_synced_at":"2026-01-11T13:27:55.030Z","repository":{"id":13606189,"uuid":"16299156","full_name":"jonschlinkert/gray-matter","owner":"jonschlinkert","description":"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","archived":false,"fork":false,"pushed_at":"2024-04-13T14:41:54.000Z","size":338,"stargazers_count":4119,"open_issues_count":66,"forks_count":142,"subscribers_count":28,"default_branch":"master","last_synced_at":"2025-05-06T21:06:14.488Z","etag":null,"topics":["assemble","config","data","front-matter","front-matter-parsers","frontmatter","gatsby","javascript","jonschlinkert","mapbox","markdown","matter","metalsmith","netlify","node","nodejs","parse","phenomic","yaml"],"latest_commit_sha":null,"homepage":"https://github.com/jonschlinkert","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jonschlinkert.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2014-01-28T01:45:48.000Z","updated_at":"2025-05-05T16:08:31.000Z","dependencies_parsed_at":"2022-08-03T09:30:41.038Z","dependency_job_id":"b168a809-d23e-442f-afd8-e9c64e0d5637","html_url":"https://github.com/jonschlinkert/gray-matter","commit_stats":{"total_commits":210,"total_committers":22,"mean_commits":9.545454545454545,"dds":"0.42380952380952386","last_synced_commit":"a5726b04f3167fadc764241deb545518c454eb82"},"previous_names":["assemble/gray-matter"],"tags_count":46,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jonschlinkert%2Fgray-matter","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jonschlinkert%2Fgray-matter/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jonschlinkert%2Fgray-matter/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jonschlinkert%2Fgray-matter/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jonschlinkert","download_url":"https://codeload.github.com/jonschlinkert/gray-matter/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253765242,"owners_count":21960695,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["assemble","config","data","front-matter","front-matter-parsers","frontmatter","gatsby","javascript","jonschlinkert","mapbox","markdown","matter","metalsmith","netlify","node","nodejs","parse","phenomic","yaml"],"created_at":"2024-07-31T09:01:00.432Z","updated_at":"2026-01-11T13:27:55.017Z","avatar_url":"https://github.com/jonschlinkert.png","language":"JavaScript","funding_links":["https://github.com/sponsors/jonschlinkert"],"categories":["JavaScript",":blue_heart: Typescript","yaml"],"sub_categories":[":books: Libraries"],"readme":"# gray-matter [![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)\n\n\u003e 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.\n\nPlease consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support.\n\n## Install\n\nInstall with [npm](https://www.npmjs.com/):\n\n```sh\n$ npm install --save gray-matter\n```\n\n## Heads up!\n\nPlease see the [changelog](CHANGELOG.md) to learn about breaking changes that were made in v3.0.\n\n\u003cbr /\u003e\n\n# Sponsors\n\nThanks to the following companies, organizations, and individuals for supporting the ongoing maintenance and development of gray-matter! [Become a Sponsor](https://github.com/sponsors/jonschlinkert) to add your logo to this README, or any of [my other projects](https://github.com/jonschlinkert?tab=repositories\u0026q=\u0026type=\u0026language=\u0026sort=stargazers)\n\n\u003cbr /\u003e\n\n## What does this do?\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cstrong\u003eRun this example\u003c/strong\u003e\u003c/summary\u003e\n\nAdd the HTML in the following example to `example.html`, then add the following code to `example.js` and run `$ node example` (without the `$`):\n\n```js\nconst fs = require('fs');\nconst matter = require('gray-matter');\nconst str = fs.readFileSync('example.html', 'utf8');\nconsole.log(matter(str));\n```\n\n\u003c/details\u003e\n\nConverts a string with front-matter, like this:\n\n```handlebars\n---\ntitle: Hello\nslug: home\n---\n\u003ch1\u003eHello world!\u003c/h1\u003e\n```\n\nInto an object like this:\n\n```js\n{\n  content: '\u003ch1\u003eHello world!\u003c/h1\u003e',\n  data: {\n    title: 'Hello',\n    slug: 'home'\n  }\n}\n```\n\n## Why use gray-matter?\n\n* **simple**: main function takes a string and returns an object\n* **accurate**: better at catching and handling edge cases than front-matter parsers that rely on regex for parsing\n* **fast**: faster than other front-matter parsers that use regex for parsing\n* **flexible**: By default, gray-matter is capable of parsing [YAML](https://github.com/nodeca/js-yaml), [JSON](http://en.wikipedia.org/wiki/Json) and JavaScript front-matter. But other [engines](#optionsengines) may be added.\n* **extensible**: Use [custom delimiters](#optionsdelimiters), or add support for [any language](#optionsengines), like [TOML](http://github.com/mojombo/toml), [CoffeeScript](http://coffeescript.org), or [CSON](https://github.com/bevry/cson)\n* **battle-tested**: used by [assemble](https://github.com/assemble/assemble), [metalsmith](https://github.com/segmentio/metalsmith), [phenomic](https://github.com/phenomic/phenomic), [verb](https://github.com/assemble/verb), [generate](https://github.com/generate/generate), [update](https://github.com/update/update) and many others.\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cstrong\u003eRationale\u003c/strong\u003e\u003c/summary\u003e\n\n**Why did we create gray-matter in the first place?**\n\nWe created gray-matter after trying out other libraries that failed to meet our standards and requirements.\n\nSome libraries met most of the requirements, but _none met all of them_.\n\n**Here are the most important**:\n\n* Be usable, if not simple\n* Use a dependable and well-supported library for parsing YAML\n* Support other languages besides YAML\n* Support stringifying back to YAML or another language\n* Don't fail when no content exists\n* Don't fail when no front matter exists\n* 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.\n* Have no problem reading YAML files directly\n* 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.\n* Support stringifying back to front-matter. This is useful for linting, updating properties, etc.\n* Allow custom delimiters, when it's necessary for avoiding delimiter collision.\n* Should return an object with at least these three properties:\n  - `data`: the parsed YAML front matter, as a JSON object\n  - `content`: the contents as a string, without the front matter\n  - `orig`: the \"original\" content (for debugging)\n\n\u003c/details\u003e\n\n## Usage\n\nUsing Node's `require()` system:\n\n```js\nconst matter = require('gray-matter');\n```\n\nOr with [typescript](https://www.typescriptlang.org)\n\n```js\nimport matter = require('gray-matter');\n// OR\nimport * as matter from 'gray-matter';\n```\n\nPass a string and [options](#options) to gray-matter:\n\n```js\nconsole.log(matter('---\\ntitle: Front Matter\\n---\\nThis is content.'));\n```\n\nReturns:\n\n```js\n{\n  content: '\\nThis is content.',\n  data: {\n    title: 'Front Matter'\n  }\n}\n```\n\nMore about the returned object in the following section.\n\n***\n\n## Returned object\n\ngray-matter returns a `file` object with the following properties.\n\n**Enumerable**\n\n* `file.data` **{Object}**: the object created by parsing front-matter\n* `file.content` **{String}**: the input string, with `matter` stripped\n* `file.excerpt` **{String}**: an excerpt, if [defined on the options](#optionsexcerpt)\n* `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](https://github.com/jonschlinkert/gray-matter/issues/65) for details regarding use case.\n* `file.isEmpty` **{Boolean}**: true if front-matter is empty.\n\n**Non-enumerable**\n\nIn addition, the following non-enumberable properties are added to the object to help with debugging.\n\n* `file.orig` **{Buffer}**: the original input string (or buffer)\n* `file.language` **{String}**: the front-matter language that was parsed. `yaml` is the default\n* `file.matter` **{String}**: the _raw_, un-parsed front-matter string\n* `file.stringify` **{Function}**: [stringify](#stringify) the file by converting `file.data` to a string in the given language, wrapping it in delimiters and prepending it to `file.content`.\n\n## Run the examples\n\nIf you'd like to test-drive the examples, first clone gray-matter into `my-project` (or wherever you want):\n\n```sh\n$ git clone https://github.com/jonschlinkert/gray-matter my-project\n```\n\nCD into `my-project` and install dependencies:\n\n```sh\n$ cd my-project \u0026\u0026 npm install\n```\n\nThen run any of the [examples](./examples) to see how gray-matter works:\n\n```sh\n$ node examples/\u003cexample_name\u003e\n```\n\n**Links to examples**\n\n* [coffee](examples/coffee.js)\n* [excerpt-separator](examples/excerpt-separator.js)\n* [excerpt-stringify](examples/excerpt-stringify.js)\n* [excerpt](examples/excerpt.js)\n* [javascript](examples/javascript.js)\n* [json-stringify](examples/json-stringify.js)\n* [json](examples/json.js)\n* [restore-empty](examples/restore-empty.js)\n* [sections-excerpt](examples/sections-excerpt.js)\n* [sections](examples/sections.js)\n* [toml](examples/toml.js)\n* [yaml-stringify](examples/yaml-stringify.js)\n* [yaml](examples/yaml.js)\n\n## API\n\n### [matter](index.js#L29)\n\nTakes 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](#returned-object).\n\n**Params**\n\n* `input` **{Object|String}**: String, or object with `content` string\n* `options` **{Object}**\n* `returns` **{Object}**\n\n**Example**\n\n```js\nconst matter = require('gray-matter');\nconsole.log(matter('---\\ntitle: Home\\n---\\nOther stuff'));\n//=\u003e { data: { title: 'Home'}, content: 'Other stuff' }\n```\n\n### [.stringify](index.js#L160)\n\nStringify 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](#engines) section to learn how to stringify other languages.\n\n**Params**\n\n* `file` **{String|Object}**: The content string to append to stringified front-matter, or a file object with `file.content` string.\n* `data` **{Object}**: Front matter to stringify.\n* `options` **{Object}**: [Options](#options) to pass to gray-matter and [js-yaml](https://github.com/nodeca/js-yaml).\n* `returns` **{String}**: Returns a string created by wrapping stringified yaml with delimiters, and appending that to the given string.\n\n**Example**\n\n```js\nconsole.log(matter.stringify('foo bar baz', {title: 'Home'}));\n// results in:\n// ---\n// title: Home\n// ---\n// foo bar baz\n```\n\n### [.read](index.js#L178)\n\nSynchronously read a file from the file system and parse front matter. Returns the same object as the [main function](#matter).\n\n**Params**\n\n* `filepath` **{String}**: file path of the file to read.\n* `options` **{Object}**: [Options](#options) to pass to gray-matter.\n* `returns` **{Object}**: Returns [an object](#returned-object) with `data` and `content`\n\n**Example**\n\n```js\nconst file = matter.read('./content/blog-post.md');\n```\n\n### [.test](index.js#L193)\n\nReturns true if the given `string` has front matter.\n\n**Params**\n\n* `string` **{String}**\n* `options` **{Object}**\n* `returns` **{Boolean}**: True if front matter exists.\n\n## Options\n\n### options.excerpt\n\n**Type**: `Boolean|Function`\n\n**Default**: `undefined`\n\nExtract an excerpt that directly follows front-matter, or is the first thing in the string if no front-matter exists.\n\nIf set to `excerpt: true`, it will look for the frontmatter delimiter, `---` by default and grab everything leading up to it.\n\n**Example**\n\n```js\nconst str = '---\\nfoo: bar\\n---\\nThis is an excerpt.\\n---\\nThis is content';\nconst file = matter(str, { excerpt: true });\n```\n\nResults in:\n\n```js\n{\n  content: 'This is an excerpt.\\n---\\nThis is content',\n  data: { foo: 'bar' },\n  excerpt: 'This is an excerpt.\\n'\n}\n```\n\nYou 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.\n\n**Example**\n\n```js\n// returns the first 4 lines of the contents\nfunction firstFourLines(file, options) {\n  file.excerpt = file.content.split('\\n').slice(0, 4).join(' ');\n}\n\nconst file =  matter([\n  '---',\n  'foo: bar',\n  '---',\n  'Only this',\n  'will be',\n  'in the',\n  'excerpt',\n  'but not this...'\n].join('\\n'), {excerpt: firstFourLines});\n```\n\nResults in:\n\n```js\n{\n  content: 'Only this\\nwill be\\nin the\\nexcerpt\\nbut not this...',\n  data: { foo: 'bar' },\n  excerpt: 'Only this will be in the excerpt'\n}\n```\n\n### options.excerpt_separator\n\n**Type**: `String`\n\n**Default**: `undefined`\n\nDefine a custom separator to use for excerpts.\n\n```js\nconsole.log(matter(string, {excerpt_separator: '\u003c!-- end --\u003e'}));\n```\n\n**Example**\n\nThe following HTML string:\n\n```html\n---\ntitle: Blog\n---\nMy awesome blog.\n\u003c!-- end --\u003e\n\u003ch1\u003eHello world\u003c/h1\u003e\n```\n\nResults in:\n\n```js\n{\n  data: { title: 'Blog'},\n  excerpt: 'My awesome blog.',\n  content: 'My awesome blog.\\n\u003c!-- end --\u003e\\n\u003ch1\u003eHello world\u003c/h1\u003e'\n}\n```\n\n### options.engines\n\nDefine custom engines for parsing and/or stringifying front-matter.\n\n**Type**: `Object` Object of engines\n\n**Default**: `JSON`, `YAML` and `JavaScript` are already handled by default.\n\n**Engine format**\n\nEngines may either be an object with `parse` and (optionally) `stringify` methods, or a function that will be used for parsing only.\n\n**Examples**\n\n```js\nconst toml = require('toml');\n\n/**\n * defined as a function\n */\n\nconst file = matter(str, {\n  engines: {\n    toml: toml.parse.bind(toml),\n  }\n});\n\n/**\n * Or as an object\n */\n\nconst file = matter(str, {\n  engines: {\n    toml: {\n      parse: toml.parse.bind(toml),\n\n      // example of throwing an error to let users know stringifying is\n      // not supported (a TOML stringifier might exist, this is just an example)\n      stringify: function() {\n        throw new Error('cannot stringify to TOML');\n      }\n    }\n  }\n});\n\nconsole.log(file);\n```\n\n### options.language\n\n**Type**: `String`\n\n**Default**: `yaml`\n\nDefine the engine to use for parsing front-matter.\n\n```js\nconsole.log(matter(string, {language: 'toml'}));\n```\n\n**Example**\n\nThe following HTML string:\n\n```html\n---\ntitle = \"TOML\"\ndescription = \"Front matter\"\ncategories = \"front matter toml\"\n---\nThis is content\n```\n\nResults in:\n\n```js\n{ content: 'This is content',\n  excerpt: '',\n  data:\n   { title: 'TOML',\n     description: 'Front matter',\n     categories: 'front matter toml' } }\n```\n\n**Dynamic language detection**\n\nInstead 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.\n\n```html\n---toml\ntitle = \"TOML\"\ndescription = \"Front matter\"\ncategories = \"front matter toml\"\n---\nThis is content\n```\n\n### options.delimiters\n\n**Type**: `String`\n\n**Default**: `---`\n\nOpen and close delimiters can be passed in as an array of strings.\n\n**Example:**\n\n```js\n// format delims as a string\nmatter.read('file.md', {delims: '~~~'});\n// or an array (open/close)\nmatter.read('file.md', {delims: ['~~~', '~~~']});\n```\n\nwould parse:\n\n```html\n~~~\ntitle: Home\n~~~\nThis is the {{title}} page.\n```\n\n## Deprecated options\n\n### options.lang\n\nDecrecated, please use [options.language](#optionslanguage) instead.\n\n### options.delims\n\nDecrecated, please use [options.delimiters](#optionsdelimiters) instead.\n\n### options.parsers\n\nDecrecated, please use [options.engines](#optionsengines) instead.\n\n## About\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cstrong\u003eContributing\u003c/strong\u003e\u003c/summary\u003e\n\nPull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cstrong\u003eRunning Tests\u003c/strong\u003e\u003c/summary\u003e\n\nRunning 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:\n\n```sh\n$ npm install \u0026\u0026 npm test\n```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cstrong\u003eBuilding docs\u003c/strong\u003e\u003c/summary\u003e\n\n_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_\n\nTo generate the readme, run the following command:\n\n```sh\n$ npm install -g verbose/verb#dev verb-generate-readme \u0026\u0026 verb\n```\n\n\u003c/details\u003e\n\n### Related projects\n\nYou might also be interested in these projects:\n\n* [assemble](https://www.npmjs.com/package/assemble): Get the rocks out of your socks! Assemble makes you fast at creating web projects… [more](https://github.com/assemble/assemble) | [homepage](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\")\n* [metalsmith](https://www.npmjs.com/package/metalsmith): An extremely simple, pluggable static site generator. | [homepage](https://metalsmith.io \"An extremely simple, pluggable static site generator.\")\n* [verb](https://www.npmjs.com/package/verb): Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used… [more](https://github.com/verbose/verb) | [homepage](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.\")\n\n### Contributors\n\n| **Commits** | **Contributor** |\n| --- | --- |\n| 179 | [jonschlinkert](https://github.com/jonschlinkert) |\n| 13  | [robertmassaioli](https://github.com/robertmassaioli) |\n| 7   | [RobLoach](https://github.com/RobLoach) |\n| 5   | [doowb](https://github.com/doowb) |\n| 5   | [heymind](https://github.com/heymind) |\n| 3   | [aljopro](https://github.com/aljopro) |\n| 3   | [shawnbot](https://github.com/shawnbot) |\n| 2   | [reccanti](https://github.com/reccanti) |\n| 2   | [onokumus](https://github.com/onokumus) |\n| 2   | [moozzyk](https://github.com/moozzyk) |\n| 2   | [ajaymathur](https://github.com/ajaymathur) |\n| 1   | [Ajedi32](https://github.com/Ajedi32) |\n| 1   | [arlair](https://github.com/arlair) |\n| 1   | [caesar](https://github.com/caesar) |\n| 1   | [ianstormtaylor](https://github.com/ianstormtaylor) |\n| 1   | [qm3ster](https://github.com/qm3ster) |\n| 1   | [zachwhaley](https://github.com/zachwhaley) |\n\n### Author\n\n**Jon Schlinkert**\n\n* [GitHub Profile](https://github.com/jonschlinkert)\n* [Twitter Profile](https://twitter.com/jonschlinkert)\n* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert)\n\n### License\n\nCopyright © 2023, [Jon Schlinkert](https://github.com/jonschlinkert).\nReleased under the [MIT License](LICENSE).\n\n***\n\n_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on July 12, 2023._\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjonschlinkert%2Fgray-matter","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjonschlinkert%2Fgray-matter","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjonschlinkert%2Fgray-matter/lists"}