版博士V2.0程序
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. # gray-matter [![NPM version](https://img.shields.io/npm/v/gray-matter.svg?style=flat)](https://www.npmjs.com/package/gray-matter) [![NPM monthly downloads](https://img.shields.io/npm/dm/gray-matter.svg?style=flat)](https://npmjs.org/package/gray-matter) [![NPM total downloads](https://img.shields.io/npm/dt/gray-matter.svg?style=flat)](https://npmjs.org/package/gray-matter) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/gray-matter.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/gray-matter)
  2. > Parse front-matter from a string or file. Fast, reliable and easy to use. Parses YAML front matter by default, but also has support for YAML, JSON, TOML or Coffee Front-Matter, with options to set custom delimiters. Used by metalsmith, assemble, verb and many other projects.
  3. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support.
  4. > NOTE: in this release we have switched over to ES Modules in the core code but both ESM and CJS are exported for users of this library.
  5. ## Install
  6. Install with [npm](https://www.npmjs.com/):
  7. ```sh
  8. npm install --save gray-matter
  9. ```
  10. ## Heads up
  11. Please see the [changelog](CHANGELOG.md) to learn about breaking changes that were made in v3.0.
  12. ## What does this do?
  13. <details>
  14. <summary><strong>Run this example</strong></summary>
  15. Add the HTML in the following example to `example.html`, then add the following code to `example.js` and run `$ node example` (without the `$`):
  16. ```js
  17. import fs from 'node:fs';
  18. import matter from 'gray-matter';
  19. const str = fs.readFileSync('example.html', 'utf8');
  20. console.log(matter(str));
  21. ```
  22. </details>
  23. Converts a string with front-matter, like this:
  24. ```handlebars
  25. ---
  26. title: Hello
  27. slug: home
  28. ---
  29. <h1>Hello world!</h1>
  30. ```
  31. Into an object like this:
  32. ```js
  33. {
  34. content: '<h1>Hello world!</h1>',
  35. data: {
  36. title: 'Hello',
  37. slug: 'home'
  38. }
  39. }
  40. ```
  41. ## Why use gray-matter?
  42. * **simple**: main function takes a string and returns an object
  43. * **accurate**: better at catching and handling edge cases than front-matter parsers that rely on regex for parsing
  44. * **fast**: faster than other front-matter parsers that use regex for parsing
  45. * **flexible**: By default, gray-matter is capable of parsing [YAML](https://github.com/nodeca/js-yaml), [JSON](http://en.wikipedia.org/wiki/Json) and JavaScript front-matter. But other [engines](#optionsengines) may be added.
  46. * **extensible**: Use [custom delimiters](#optionsdelimiters), or add support for [any language](#optionsengines), like [TOML](http://github.com/mojombo/toml), [CoffeeScript](http://coffeescript.org), or [CSON](https://github.com/bevry/cson)
  47. * **battle-tested**: used by [assemble](https://github.com/assemble/assemble), [metalsmith](https://github.com/segmentio/metalsmith), [phenomic](https://github.com/phenomic/phenomic), [verb](https://github.com/assemble/verb), [generate](https://github.com/generate/generate), [update](https://github.com/update/update) and many others.
  48. <details>
  49. <summary><strong>Rationale</strong></summary>
  50. **Why did we create gray-matter in the first place?**
  51. We created gray-matter after trying out other libraries that failed to meet our standards and requirements.
  52. Some libraries met most of the requirements, but _none met all of them_.
  53. **Here are the most important**:
  54. * Be usable, if not simple
  55. * Use a dependable and well-supported library for parsing YAML
  56. * Support other languages besides YAML
  57. * Support stringifying back to YAML or another language
  58. * Don't fail when no content exists
  59. * Don't fail when no front matter exists
  60. * Don't use regex for parsing. This is a relatively simple parsing operation, and regex is the slowest and most error-prone way to do it.
  61. * Have no problem reading YAML files directly
  62. * Have no problem with complex content, including **non-front-matter** fenced code blocks that contain examples of YAML front matter. Other parsers fail on this.
  63. * Support stringifying back to front-matter. This is useful for linting, updating properties, etc.
  64. * Allow custom delimiters, when it's necessary for avoiding delimiter collision.
  65. * Should return an object with at least these three properties:
  66. * `data`: the parsed YAML front matter, as a JSON object
  67. * `content`: the contents as a string, without the front matter
  68. * `orig`: the "original" content (for debugging)
  69. </details>
  70. ## Usage
  71. Both JS and TS use the modern "import" signature that hopefully you are familiar with:
  72. ```js
  73. import matter from 'gray-matter';
  74. ```
  75. Pass a string and [options](#options) to gray-matter:
  76. ```js
  77. console.log(matter('---\ntitle: Front Matter\n---\nThis is content.'));
  78. ```
  79. Returns:
  80. ```js
  81. {
  82. content: '\nThis is content.',
  83. data: {
  84. title: 'Front Matter'
  85. }
  86. }
  87. ```
  88. More about the returned object in the following section.
  89. ***
  90. ## Returned object
  91. gray-matter returns a `file` object with the following properties.
  92. ### Enumerable
  93. * `file.data` **{Object}**: the object created by parsing front-matter
  94. * `file.content` **{String}**: the input string, with `matter` stripped
  95. * `file.excerpt` **{String}**: an excerpt, if [defined on the options](#optionsexcerpt)
  96. * `file.empty` **{String}**: when the front-matter is "empty" (either all whitespace, nothing at all, or just comments and no data), the original string is set on this property. See [#65](https://github.com/jonschlinkert/gray-matter/issues/65) for details regarding use case.
  97. * `file.isEmpty` **{Boolean}**: true if front-matter is empty.
  98. ### Non-enumerable
  99. In addition, the following non-enumberable properties are added to the object to help with debugging.
  100. * `file.orig` **{Buffer}**: the original input string (or buffer)
  101. * `file.language` **{String}**: the front-matter language that was parsed. `yaml` is the default
  102. * `file.matter` **{String}**: the _raw_, un-parsed front-matter string
  103. * `file.stringify` **{Function}**: [stringify](#stringify) the file by converting `file.data` to a string in the given language, wrapping it in delimiters and prepending it to `file.content`.
  104. ## Run the examples
  105. If you'd like to test-drive the examples, first clone gray-matter into `my-project` (or wherever you want):
  106. ```sh
  107. git clone https://github.com/jonschlinkert/gray-matter my-project
  108. ```
  109. CD into `my-project` and install dependencies:
  110. ```sh
  111. cd my-project && npm install
  112. ```
  113. Then run any of the [examples](./examples) to see how gray-matter works:
  114. ```sh
  115. node examples/<example_name>
  116. ```
  117. ### Links to examples
  118. * [coffee](examples/coffee.js)
  119. * [excerpt-separator](examples/excerpt-separator.js)
  120. * [excerpt-stringify](examples/excerpt-stringify.js)
  121. * [excerpt](examples/excerpt.js)
  122. * [javascript](examples/javascript.js)
  123. * [json-stringify](examples/json-stringify.js)
  124. * [json](examples/json.js)
  125. * [restore-empty](examples/restore-empty.js)
  126. * [sections-excerpt](examples/sections-excerpt.js)
  127. * [sections](examples/sections.js)
  128. * [toml](examples/toml.js)
  129. * [yaml-stringify](examples/yaml-stringify.js)
  130. * [yaml](examples/yaml.js)
  131. ## API
  132. ### [matter](index.js#L29)
  133. Takes a string or object with `content` property, extracts and parses front-matter from the string, then returns an object with `data`, `content` and other [useful properties](#returned-object).
  134. **Params**
  135. * `input` **{Object|String}**: String, or object with `content` string
  136. * `options` **{Object}**
  137. * `returns` **{Object}**
  138. **Example**
  139. ```js
  140. import matter from 'gray-matter';
  141. console.log(matter('---\ntitle: Home\n---\nOther stuff'));
  142. //=> { data: { title: 'Home'}, content: 'Other stuff' }
  143. ```
  144. ### [.stringify](index.js#L160)
  145. Stringify an object to YAML or the specified language, and append it to the given string. By default, only YAML and JSON can be stringified. See the [engines](#engines) section to learn how to stringify other languages.
  146. **Params**
  147. * `file` **{String|Object}**: The content string to append to stringified front-matter, or a file object with `file.content` string.
  148. * `data` **{Object}**: Front matter to stringify.
  149. * `options` **{Object}**: [Options](#options) to pass to gray-matter and [js-yaml](https://github.com/nodeca/js-yaml).
  150. * `returns` **{String}**: Returns a string created by wrapping stringified yaml with delimiters, and appending that to the given string.
  151. **Example**
  152. ```js
  153. console.log(matter.stringify('foo bar baz', {title: 'Home'}));
  154. // results in:
  155. // ---
  156. // title: Home
  157. // ---
  158. // foo bar baz
  159. ```
  160. ### [.read](index.js#L178)
  161. Synchronously read a file from the file system and parse front matter. Returns the same object as the [main function](#matter).
  162. **Params**
  163. * `filepath` **{String}**: file path of the file to read.
  164. * `options` **{Object}**: [Options](#options) to pass to gray-matter.
  165. * `returns` **{Object}**: Returns [an object](#returned-object) with `data` and `content`
  166. **Example**
  167. ```js
  168. const file = matter.read('./content/blog-post.md');
  169. ```
  170. ### [.test](index.js#L193)
  171. Returns true if the given `string` has front matter.
  172. **Params**
  173. * `string` **{String}**
  174. * `options` **{Object}**
  175. * `returns` **{Boolean}**: True if front matter exists.
  176. ## Options
  177. ### options.excerpt
  178. **Type**: `Boolean|Function`
  179. **Default**: `undefined`
  180. Extract an excerpt that directly follows front-matter, or is the first thing in the string if no front-matter exists.
  181. If set to `excerpt: true`, it will look for the frontmatter delimiter, `---` by default and grab everything leading up to it.
  182. **Example**
  183. ```js
  184. const str = '---\nfoo: bar\n---\nThis is an excerpt.\n---\nThis is content';
  185. const file = matter(str, { excerpt: true });
  186. ```
  187. Results in:
  188. ```js
  189. {
  190. content: 'This is an excerpt.\n---\nThis is content',
  191. data: { foo: 'bar' },
  192. excerpt: 'This is an excerpt.\n'
  193. }
  194. ```
  195. You can also set `excerpt` to a function. This function uses the 'file' and 'options' that were initially passed to gray-matter as parameters, so you can control how the excerpt is extracted from the content.
  196. **Example**
  197. ```js
  198. // returns the first 4 lines of the contents
  199. function firstFourLines(file, options) {
  200. file.excerpt = file.content.split('\n').slice(0, 4).join(' ');
  201. }
  202. const file = matter([
  203. '---',
  204. 'foo: bar',
  205. '---',
  206. 'Only this',
  207. 'will be',
  208. 'in the',
  209. 'excerpt',
  210. 'but not this...'
  211. ].join('\n'), {excerpt: firstFourLines});
  212. ```
  213. Results in:
  214. ```js
  215. {
  216. content: 'Only this\nwill be\nin the\nexcerpt\nbut not this...',
  217. data: { foo: 'bar' },
  218. excerpt: 'Only this will be in the excerpt'
  219. }
  220. ```
  221. ### options.excerpt_separator
  222. **Type**: `String`
  223. **Default**: `undefined`
  224. Define a custom separator to use for excerpts.
  225. ```js
  226. console.log(matter(string, {excerpt_separator: '<!-- end -->'}));
  227. ```
  228. **Example**
  229. The following HTML string:
  230. ```html
  231. ---
  232. title: Blog
  233. ---
  234. My awesome blog.
  235. <!-- end -->
  236. <h1>Hello world</h1>
  237. ```
  238. Results in:
  239. ```js
  240. {
  241. data: { title: 'Blog'},
  242. excerpt: 'My awesome blog.',
  243. content: 'My awesome blog.\n<!-- end -->\n<h1>Hello world</h1>'
  244. }
  245. ```
  246. ### options.engines
  247. Define custom engines for parsing and/or stringifying front-matter.
  248. **Type**: `Object` Object of engines
  249. **Default**: `JSON`, `YAML` and `JavaScript` are already handled by default.
  250. **Engine format**
  251. Engines may either be an object with `parse` and (optionally) `stringify` methods, or a function that will be used for parsing only.
  252. **Examples**
  253. ```js
  254. const toml = require('toml');
  255. /**
  256. * defined as a function
  257. */
  258. const file = matter(str, {
  259. engines: {
  260. toml: toml.parse.bind(toml),
  261. }
  262. });
  263. /**
  264. * Or as an object
  265. */
  266. const file = matter(str, {
  267. engines: {
  268. toml: {
  269. parse: toml.parse.bind(toml),
  270. // example of throwing an error to let users know stringifying is
  271. // not supported (a TOML stringifier might exist, this is just an example)
  272. stringify: function() {
  273. throw new Error('cannot stringify to TOML');
  274. }
  275. }
  276. }
  277. });
  278. console.log(file);
  279. ```
  280. ### options.language
  281. **Type**: `String`
  282. **Default**: `yaml`
  283. Define the engine to use for parsing front-matter.
  284. ```js
  285. console.log(matter(string, {language: 'toml'}));
  286. ```
  287. **Example**
  288. The following HTML string:
  289. ```html
  290. ---
  291. title = "TOML"
  292. description = "Front matter"
  293. categories = "front matter toml"
  294. ---
  295. This is content
  296. ```
  297. Results in:
  298. ```js
  299. { content: 'This is content',
  300. excerpt: '',
  301. data:
  302. { title: 'TOML',
  303. description: 'Front matter',
  304. categories: 'front matter toml' } }
  305. ```
  306. **Dynamic language detection**
  307. Instead of defining the language on the options, gray-matter will automatically detect the language defined after the first delimiter and select the correct engine to use for parsing.
  308. ```html
  309. ---toml
  310. title = "TOML"
  311. description = "Front matter"
  312. categories = "front matter toml"
  313. ---
  314. This is content
  315. ```
  316. ### options.delimiters
  317. **Type**: `String`
  318. **Default**: `---`
  319. Open and close delimiters can be passed in as an array of strings.
  320. **Example:**
  321. ```js
  322. // format delims as a string
  323. matter.read('file.md', {delims: '~~~'});
  324. // or an array (open/close)
  325. matter.read('file.md', {delims: ['~~~', '~~~']});
  326. ```
  327. would parse:
  328. ```html
  329. ~~~
  330. title: Home
  331. ~~~
  332. This is the {{title}} page.
  333. ```
  334. ## Deprecated options
  335. ### options.lang
  336. Decrecated, please use [options.language](#optionslanguage) instead.
  337. ### options.delims
  338. Decrecated, please use [options.delimiters](#optionsdelimiters) instead.
  339. ### options.parsers
  340. Decrecated, please use [options.engines](#optionsengines) instead.
  341. ## About
  342. <details>
  343. <summary><strong>Contributing</strong></summary>
  344. Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
  345. </details>
  346. <details>
  347. <summary><strong>Running Tests</strong></summary>
  348. Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
  349. ```sh
  350. npm install && npm test
  351. ```
  352. </details>
  353. <details>
  354. <summary><strong>Building docs</strong></summary>
  355. _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
  356. To generate the readme, run the following command:
  357. ```sh
  358. npm install -g verbose/verb#dev verb-generate-readme && verb
  359. ```
  360. </details>
  361. ### Related projects
  362. You might also be interested in these projects:
  363. * [assemble](https://www.npmjs.com/package/assemble): Get the rocks out of your socks! Assemble makes you fast at creating web projects… [more](https://github.com/assemble/assemble) | [homepage](https://github.com/assemble/assemble "Get the rocks out of your socks! Assemble makes you fast at creating web projects. Assemble is used by thousands of projects for rapid prototyping, creating themes, scaffolds, boilerplates, e-books, UI components, API documentation, blogs, building websit")
  364. * [metalsmith](https://www.npmjs.com/package/metalsmith): An extremely simple, pluggable static site generator. | [homepage](https://github.com/segmentio/metalsmith#readme "An extremely simple, pluggable static site generator.")
  365. * [verb](https://www.npmjs.com/package/verb): Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used… [more](https://github.com/verbose/verb) | [homepage](https://github.com/verbose/verb "Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used on hundreds of projects of all sizes to generate everything from API docs to readmes.")
  366. * [gray-matter-loader](https://github.com/atlassian/gray-matter-loader): A webpack loader for gray-matter. [homepage](https://github.com/atlassian/gray-matter-loader#gray-matter-loader)
  367. ### Contributors
  368. | **Commits** | **Contributor** |
  369. | ----------- | --------------------------------------------------- |
  370. | 174 | [jonschlinkert](https://github.com/jonschlinkert) |
  371. | 7 | [RobLoach](https://github.com/RobLoach) |
  372. | 5 | [heymind](https://github.com/heymind) |
  373. | 4 | [doowb](https://github.com/doowb) |
  374. | 3 | [aljopro](https://github.com/aljopro) |
  375. | 2 | [reccanti](https://github.com/reccanti) |
  376. | 2 | [onokumus](https://github.com/onokumus) |
  377. | 2 | [moozzyk](https://github.com/moozzyk) |
  378. | 1 | [Ajedi32](https://github.com/Ajedi32) |
  379. | 1 | [caesar](https://github.com/caesar) |
  380. | 1 | [ianstormtaylor](https://github.com/ianstormtaylor) |
  381. | 1 | [qm3ster](https://github.com/qm3ster) |
  382. | 1 | [zachwhaley](https://github.com/zachwhaley) |
  383. ### Author
  384. **Jon Schlinkert**
  385. * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert)
  386. * [GitHub Profile](https://github.com/jonschlinkert)
  387. * [Twitter Profile](https://twitter.com/jonschlinkert)
  388. ### License
  389. Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert).
  390. Released under the [MIT License](LICENSE).
  391. ***
  392. _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on April 01, 2018._