Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
gray-matter
Advanced tools
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
The gray-matter npm package is used to parse front-matter from strings or files. Front-matter is metadata stored at the top of a file, typically in YAML or JSON format, which is often used in static site generators and other content management systems.
Parsing Front-Matter
This feature allows you to parse front-matter from a string. The front-matter is typically written in YAML or JSON format and is separated from the content by triple dashes (---). The parsed object contains the metadata and the content separately.
const matter = require('gray-matter');
const file = '---\ntitle: Hello World\ndate: 2023-10-01\n---\nThis is the content of the file.';
const parsed = matter(file);
console.log(parsed);
Stringify Front-Matter
This feature allows you to convert a content string and a metadata object back into a string with front-matter. This is useful for generating files with front-matter programmatically.
const matter = require('gray-matter');
const data = { title: 'Hello World', date: '2023-10-01' };
const content = 'This is the content of the file.';
const stringified = matter.stringify(content, data);
console.log(stringified);
Custom Delimiters
This feature allows you to specify custom delimiters for the front-matter. By default, gray-matter uses triple dashes (---), but you can change this to any string you prefer.
const matter = require('gray-matter');
const file = '+++\ntitle = "Hello World"\ndate = "2023-10-01"\n+++\nThis is the content of the file.';
const parsed = matter(file, { delimiters: '+++' });
console.log(parsed);
The front-matter package is another tool for parsing front-matter from strings. It is simpler and has fewer features compared to gray-matter, but it is also lightweight and easy to use.
The js-yaml package is primarily used for parsing and stringifying YAML, but it can also be used to handle front-matter. It is more general-purpose and powerful for YAML processing, but it requires more setup to use for front-matter specifically.
The marked package is a markdown parser that can also handle front-matter if used in conjunction with other tools. It is more focused on converting markdown to HTML, but it can be extended to support front-matter parsing.
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.
Install with npm:
$ npm install --save gray-matter
Please see the release history to learn about breaking changes that were made in v3.0.
Add the HTML in the following example to example.html
, then add the following code to example.js
and run $ node example
(without the $
):
var fs = require('fs');
var matter = require('gray-matter');
var 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 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:
data
: the parsed YAML front matter, as a JSON objectcontent
: the contents as a string, without the front matterorig
: the "original" contentUsing Node's require()
system:
var 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.
gray-matter returns a file
object with the following properties.
Enumerable
file.data
{Object}: the object created by parsing front-matterfile.content
{String}: the input string, with matter
strippedfile.excerpt
{String}: an excerpt, if defined on the optionsNon-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 defaultfile.matter
{String}: the raw, un-parsed front-matter stringfile.stringify
{Function}: stringify the file by converting file.data
to a string in the given language, wrapping it in delimiters and appending it to file.content
.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>
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
stringoptions
{Object}returns
{Object}Example
var matter = require('gray-matter');
console.log(matter('---\ntitle: Home\n---\nOther stuff'));
//=> { data: { title: 'Home'}, content: 'Other stuff' }
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
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
var file = matter.read('./content/blog-post.md');
Returns true if the given string
has front matter.
Params
string
{String}options
{Object}returns
{Boolean}: True if front matter exists.Type: Object
Default: undefined
Extract an excerpt that directly follows front-matter, or is the first thing in the string if no front-matter exists.
Example
var str = '--\ntitle: Home\n---\nAn excerpt\n---\nOther stuff';
console.log(matter(str, {excerpt: true}));
Results in:
{
data: { title: 'Home'},
excerpt: '\nAn excerpt',
content: '\nAn excerpt\n---\nOther stuff'
}
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>'
}
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
var toml = require('toml');
/**
* defined as a function
*/
var file = matter(str, {
engines: {
toml: toml.parse.bind(toml),
}
});
/**
* Or as an object
*/
var 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);
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
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.
Decrecated, please use options.language instead.
Decrecated, please use options.delimiters instead.
Decrecated, please use options.engines instead.
options.parsers
was renamed to options.enginesmatter
and stringify
propertiesBreaking changes
toml
, coffee
and cson
are no longer supported by default. Please see options.engines and the examples to learn how to add engines.Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.
Commits | Contributor |
---|---|
128 | jonschlinkert |
7 | RobLoach |
5 | heymind |
2 | doowb |
2 | onokumus |
2 | moozzyk |
1 | Ajedi32 |
1 | ianstormtaylor |
(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
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
Jon Schlinkert
Copyright © 2017, Jon Schlinkert. Released under the MIT License.
This file was generated by verb-generate-readme, v0.6.0, on June 30, 2017.
FAQs
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
The npm package gray-matter receives a total of 674,022 weekly downloads. As such, gray-matter popularity was classified as popular.
We found that gray-matter demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.