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);