jonschlinkert / gray-matter

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

Home Page:https://github.com/jonschlinkert

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to use async or Promise.then()

josineto opened this issue · comments

How can I use gray-matter in a asynchronous way? It doesn't offer even a callback function (which would allow one to use utils.promisify).

gray-matter is synchronous so there is no need to use async or Promise.then().

Sorry, I think I didn't explained well: is there a way to use read function asynchronously?

I wish to use gray-matter in a Node.js application, which needs all file operations be performed asynchronously.

In that case, you could read the file in first, then pass it to gray-matter:

const fs = require('fs').promises;
const matter = require('gray-matter');

const read = async (filepath, options) {
  const str = await fs.readFile(filepath, 'utf8');
  const file = matter(str, options);
  file.path = filepath;
  return file;
};

The above will give you a .read method that looks like matter.read, but is async and can be used like:

const file = await read('./path/to/my-file.md');

If you just want to get the file object back "as-is" without adding the .path to it, you can also do something like this...

const filepath = './path/to/my-file.md';
const str = await fs.readFile(filepath, 'utf8');
const file = matter(str);