What is front-matter?
The front-matter npm package is used to parse YAML or JSON front matter from strings, typically used in markdown files. This is useful for extracting metadata from content files.
What are front-matter's main functionalities?
Parsing Front Matter
This feature allows you to parse a string containing front matter and extract the metadata and content separately.
const frontMatter = require('front-matter');
const content = '---\ntitle: Hello World\ndate: 2023-10-01\n---\nThis is the content of the file.';
const parsed = frontMatter(content);
console.log(parsed.attributes); // { title: 'Hello World', date: '2023-10-01' }
console.log(parsed.body); // 'This is the content of the file.'
Custom Delimiters
This feature allows you to specify custom delimiters for the front matter, which is useful if your front matter is not delimited by the default '---'.
const frontMatter = require('front-matter');
const content = '+++\ntitle: Hello World\ndate: 2023-10-01\n+++\nThis is the content of the file.';
const options = { delimiters: '+++' };
const parsed = frontMatter(content, options);
console.log(parsed.attributes); // { title: 'Hello World', date: '2023-10-01' }
console.log(parsed.body); // 'This is the content of the file.'
Other packages similar to front-matter
gray-matter
gray-matter is a popular package for parsing front matter from strings. It supports YAML, JSON, and TOML front matter, and offers more features like custom engines and stringifying parsed data back to front matter format. It is more feature-rich compared to front-matter.
front-matter
Extract YAML front matter from strings.
This modules does not do any IO (file loading or reading), only extracting yaml front matter from strings.
This concept that was originally introduced to me through the jeykll blogging system and is pretty useful where you want to be able to easily add metadata to content without the need for a database. YAML is extracted from the the top of a file between matching separators of "---" or "= yaml =".
Example
So you have a file example.md
:
---
title: Just hack'n
description: Nothing to see here
---
This is some text about some stuff that happened sometime ago
Then you can do this:
var fs = require('fs')
, fm = require('front-matter')
fs.readFile('./example.md', 'utf8', function(err, data){
if (err) throw err
var content = fm(data)
console.log(content)
})
And end up with an object like this:
{ attributes: { title: 'Just hack\'n'
, description: 'Nothing to see here'
}
, body: 'This is some content'
}
Methods
var fm = require('front-matter')
fm(string)
Return a content
object with two properties:
content.attributes
contains the extracted yaml attributes in json formcontent.body
contains the string contents below the yaml separators
Install
With npm do:
npm install front-matter
License
MIT