Extract dedicated code blocks from markdown files to “real” code files

Scan a Markdown file for code blocks prepended with a local file link and write the code block’s content to the file defined in the link, the file / path of the link are created if not existing yet.

Basic use case is e.g. to validate code examples in a README.md, use them directly for automated tests and reuse them for demos, i.e. to avoid the effort and notorious errors with copy and paste of code and divergence of intentionally identical code at different places.

Also possible is e.g. extracting examples from the README.md of another project to reuse them in the current project or pushing examples of the current project to a centralized storage.

The basic idea and code is forked from the ingenious markdown-code-extractor (v1.4.0).

hh lohmann <hh.lohmann@gmail.com>

Synopsis

  import { markdownCodeExtract } from 'markdown-code-extract'

  [await] markdownCodeExtract()

  [await] markdownCodeExtract(mdFile)

  [await] markdownCodeExtract(mdFile,outputRoot)

  [await] markdownCodeExtract('examples.md')

  [await] markdownCodeExtract('../examples/js.md')

  [await] markdownCodeExtract('#','../examples/js.md')

Parameters

mdFile

Optional: Name / path of Markdown file to extract code blocks from

outputRoot

Optional: Path of an existing directory to write code files to

logLevel

Optional: Log process details

Returns

Promise

Demo

See demos on GitHub Pages for this repo

Dependencies

Installation

Pick for your preferred package manager:

  npm i markdown-code-extract
  pnpm i markdown-code-extract
  bun i markdown-code-extract
  # For Yarn you should double check docs for your and / or
  # current Yarn version, newer versions do not treat `i package_name`
  # as an alias for `add ...` and exclude global installations
  yarn add markdown-code-extract

Source Code

License

References

is-binary-file-simple

markdown-code-extractor

Endspacer: './markdown-assets/endspacer.png' missing - see https://hh-lohmann.github.io/html-endspacer
[top]