Introduction to Gray-Matter
Gray-Matter is a powerful library used for parsing and stringifying front matter, a form of meta-data for files. By analyzing the front matter, users can leverage the stored metadata in their applications efficiently.
Basic Usage
The primary function of Gray-Matter is to parse front matter from strings. Here’s a simple example:
const matter = require('gray-matter'); const file = matter('---\ntitle: Blog Post\n---\nContent of the blog post.'); console.log(file); // Outputs: // {data: { title: 'Blog Post' }, content: 'Content of the blog post.', ...}
Supported Formats
- YAML: Default format.
- JSON: Can be configured using options.
- TOML: Supported out of the box.
YAML Front Matter
Here’s an example of parsing YAML front matter:
const yamlString = '---\ntitle: YAML Example\ndescription: A brief YAML example\n---\nSome content here.'; const parsed = matter(yamlString); console.log(parsed.data); // Outputs: // { title: 'YAML Example', description: 'A brief YAML example' }
JSON Front Matter
To parse JSON front matter:
const jsonString = ';;;\n{"title": "JSON Example", "published": true}\n;;;\nMore content here.'; const parsedJson = matter(jsonString, { delimiter: ';;;' }); console.log(parsedJson.data); // Outputs: // { title: 'JSON Example', published: true }
TOML Front Matter
Parsing TOML front matter looks like this:
const tomlString = '+++\ntitle = "TOML Example"\n+++\nContent follows.'; const parsedToml = matter(tomlString); console.log(parsedToml.data); // Outputs: // { title: 'TOML Example' }
Stringifying Content
Converting metadata and content back to string with front matter is straightforward:
const content = matter.stringify('Some content.', { title: 'New Post', author: 'John Doe' }); console.log(content); // Outputs: // --- // title: New Post // author: John Doe // --- // Some content.
Usage in an Application
Below is an example of a simple Node.js application using Gray-Matter:
const fs = require('fs'); const matter = require('gray-matter');
// Read a markdown file fs.readFile('example.md', 'utf8', (err, data) => {
if (err) throw err;
// Parse the file
const file = matter(data);
// Display the parsed data
console.log(file.data); // Metadata
console.log(file.content); // Content
});