npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

marked-hook-data

v1.3.6

Published

A sequential hook for marked to load data from files or objects

Downloads

28

Readme

marked-hook-data

A sequential hook for marked to load data from files or objects and attach it to the marked hooks context. This hook allows you to enrich your Markdown processing by including external data seamlessly.

Install

You can install marked-hook-data using npm or yarn:

npm i marked-sequential-hooks marked-hook-data
# or
yarn add marked-sequential-hooks marked-hook-data

Usage

Once you've installed this hook, you can use it in your marked configuration. Here's an example of how to configure it:

Node.js

Say we have the following file example.md:

---
layout: 'single-post'
datasource: './posts.json'
---

# {title}

{body}

The file posts.json would look something like:

[
  {
    "title": "My First Post",
    "body": "Hello World!"
  },
  {
    "title": "My Second Post",
    "body": "Hello Again!"
  },
  {
    "title": "My Third Post",
    "body": "Hello Again and Again!"
  }
]

And our module example.js looks as follows:

import { readFileSync } from 'node:fs'
import { Marked } from 'marked'
import markedSequentialHooks from 'marked-sequential-hooks'
import markedHookData from 'marked-hook-data'
import markedHookFrontmatter from 'marked-hook-frontmatter'
import pupa from 'pupa'

const template = readFileSync('example.md', 'utf8')

new Marked()
  .use(
    markedSequentialHooks({
      markdownHooks: [markedHookFrontmatter(), markedHookData()],
      htmlHooks: [
        (html, data) => {
          for (const post of data.posts) {
            const filename =
              post.title.toLowerCase().replace(/[^\w-]+/g, '-') + '.html'
            const content = pupa(html, post)

            console.log('filename:', filename)
            console.log(content)
            console.log('=====\n')
          }

          return html
        }
      ]
    })
  )
  .parse(template)

Now, running node example.js yields:

filename: my-first-post.html
<h1>My First Post</h1>
<p>Hello World!</p>

=====

filename: my-second-post.html
<h1>My Second Post</h1>
<p>Hello Again!</p>

=====

filename: my-third-post.html
<h1>My Third Post</h1>
<p>Hello Again and Again!</p>

=====

Browser

Say we have the following file example.html:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Marked hook data</title>
  </head>
  <body>
    <h1>My Posts</h1>
    <div id="content"></div>

    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/marked-sequential-hooks/dist/index.umd.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/marked-hook-data/dist/index.umd.min.js"></script>
    <script>
      ;(async () => {
        const res = await fetch('https://dummyjson.com/posts?limit=10')
        const dataPosts = await res.json()

        document.getElementById('content').innerHTML = await new marked.Marked({
          async: true
        })
          .use(
            markedSequentialHooks({
              markdownHooks: [
                markedHookData(dataPosts),
                (markdown, { posts = [] }) => {
                  const chunk = []

                  for (const { title, body } of posts) {
                    chunk.push(
                      markdown.replace('{title}', title).replace('{body}', body)
                    )
                  }

                  return chunk.join('\n')
                }
              ]
            })
          )
          .parse('## {title}\n\n{body}\n\n---\n')
      })()
    </script>
  </body>
</html>

Try marked-hook-data on RunKit

Function

markedHookData(source: string | string[] | { [key: string]: any }): MarkdownHook

  • source: A string or array of string specifying file patterns or an object containing data.
  • Returns: A MarkdownHook function that processes the Markdown and attaches hooks data.

Loading Data from Files

marked-hook-data allows you to load data from files and attach it to the hooks context.

Loading Data from Files by File Patterns

To load data from files based on file patterns, provide a string argument with the file patterns:

// work well witn async option
marked.use({ async: true }).use(markedHookData('data/*.json'))

This example will load all JSON files in the data directory and attach their content to the hooks context.

Loading Data from Specific Files

To load data from specific files, provide the file paths directly in an array:

marked.use(markedHookData(['data/file1.json', 'data/file2.yaml']))

This example will load data from file1.json and file2.yaml and attach it to the hooks context.

Supported File Types

marked-hook-data supports loading the following file types:

  • .yaml and .yml
  • .json
  • .js, .mjs, and .cjs – ESM files are only supported when the async option is set to true.

Loading Data from Objects

You can also directly provide an object:

const externalData = {
  greeting: 'Hello, World!',
  author: 'John Doe'
}

marked.use(markedHookData(externalData))

This object will be attached to the hooks context.

Related

Contributing

We 💛  issues.

When committing, please conform to the semantic-release commit standards. Please install commitizen and the adapter globally, if you have not already.

npm i -g commitizen cz-conventional-changelog

Now you can use git cz or just cz instead of git commit when committing. You can also use git-cz, which is an alias for cz.

git add . && git cz

License

GitHub

A project by Stilearning © 2023-2024.