209 lines
8.8 KiB
Markdown
209 lines
8.8 KiB
Markdown
|
# @push.rocks/smartfm
|
|||
|
|
|||
|
The `@push.rocks/smartfm` module handles frontmatter data in markdown and other text files. The module allows easy parsing, stringification, and extraction of frontmatter data, using YAML or JSON format. It leverages the `gray-matter` library for advanced functionality with a simple API.
|
|||
|
|
|||
|
## Install
|
|||
|
|
|||
|
To use `@push.rocks/smartfm`, you first need to install it via npm. Make sure you have Node.js installed, and run the following command in your terminal:
|
|||
|
|
|||
|
```sh
|
|||
|
npm install @push.rocks/smartfm
|
|||
|
```
|
|||
|
|
|||
|
This will add the module as a dependency to your project.
|
|||
|
|
|||
|
## Usage
|
|||
|
|
|||
|
Once the module is installed, you can start using its capabilities by importing and initializing the `Smartfm` class in your TypeScript or JavaScript projects. The following sections provide comprehensive examples of the module's functionality:
|
|||
|
|
|||
|
### Importing the Module
|
|||
|
|
|||
|
To get started with the module, use the following import statement:
|
|||
|
|
|||
|
```typescript
|
|||
|
import { Smartfm } from '@push.rocks/smartfm';
|
|||
|
```
|
|||
|
|
|||
|
The module exports the `Smartfm` class, which you will use to manipulate frontmatter in your files.
|
|||
|
|
|||
|
### Initializing the `Smartfm` Class
|
|||
|
|
|||
|
The `Smartfm` class requires an options object to be passed during initialization. The options object specifies the type of frontmatter format you are working with, which can either be `'yaml'` or `'json'`. Here's how you can initialize the class:
|
|||
|
|
|||
|
```typescript
|
|||
|
// Initialize with YAML frontmatter
|
|||
|
let smartfm = new Smartfm({ fmType: 'yaml' });
|
|||
|
|
|||
|
// Initialize with JSON frontmatter
|
|||
|
let smartfmJSON = new Smartfm({ fmType: 'json' });
|
|||
|
```
|
|||
|
|
|||
|
The initialized objects can then be used to parse and stringify frontmatter in strings and text files.
|
|||
|
|
|||
|
### Parsing Frontmatter from Strings
|
|||
|
|
|||
|
To parse frontmatter data from a string that includes frontmatter, use the `parse` method. This function returns an object containing the parsed frontmatter data and the rest of the string:
|
|||
|
|
|||
|
```typescript
|
|||
|
const sampleString = `---
|
|||
|
title: Test Document
|
|||
|
author: John Doe
|
|||
|
---
|
|||
|
This is the body content of the file.`;
|
|||
|
|
|||
|
let parsedContent = smartfm.parse(sampleString);
|
|||
|
console.log(parsedContent.data); // Outputs the frontmatter data as a JavaScript object
|
|||
|
console.log(parsedContent.content); // Outputs "This is the body content of the file."
|
|||
|
```
|
|||
|
|
|||
|
The `parse` method will recognize and extract the frontmatter block, returning it as a JavaScript object while preserving the original content of the string.
|
|||
|
|
|||
|
### Stringifying a String with Frontmatter
|
|||
|
|
|||
|
If you have a string and frontmatter data that you want to combine into a correctly formatted frontmatter block in a string, you can use the `stringify` method:
|
|||
|
|
|||
|
```typescript
|
|||
|
const bodyContent = "This is some markdown content.";
|
|||
|
const frontmatterData = {
|
|||
|
date: "2023-01-01",
|
|||
|
tags: ["example", "frontmatter"]
|
|||
|
};
|
|||
|
|
|||
|
let combinedString = smartfm.stringify(bodyContent, frontmatterData);
|
|||
|
console.log(combinedString);
|
|||
|
// Outputs a string with the frontmatter serialized at the top
|
|||
|
```
|
|||
|
|
|||
|
This method appends the serialized frontmatter to the top of the given body content, making it ready for use in typical markdown or frontmatter-supported documents.
|
|||
|
|
|||
|
### Parsing Frontmatter from Commented Sections
|
|||
|
|
|||
|
Sometimes frontmatter data might be commented out. The `parseFromComments` method allows you to parse such data by providing a comment prefix:
|
|||
|
|
|||
|
```typescript
|
|||
|
const commentedFile = `# ---
|
|||
|
# title: Commented Example
|
|||
|
# date: 2023-10-15
|
|||
|
# ---
|
|||
|
Actual file content here...`;
|
|||
|
|
|||
|
let parsedCommentedContent = smartfm.parseFromComments('# ', commentedFile);
|
|||
|
console.log(parsedCommentedContent.data); // Outputs { title: "Commented Example", date: "2023-10-15" }
|
|||
|
```
|
|||
|
|
|||
|
The `parseFromComments` method strips the comment prefixes before parsing the frontmatter, enabling easy extraction of data listed in commented sections.
|
|||
|
|
|||
|
### Using the Module for Complex Scenarios
|
|||
|
|
|||
|
Beyond these basic operations, the `@push.rocks/smartfm` module can be a crucial part of more complex workflows. For instance, integrating frontmatter management with static site generators, content management systems (CMS), or any situation where content metadata is necessary.
|
|||
|
|
|||
|
#### Example Scenario: A Static Site Generator
|
|||
|
|
|||
|
Imagine a static site generator that uses markdown files with frontmatter as data sources for pages. `@push.rocks/smartfm` can help read, extract, and manipulate these files programmatically:
|
|||
|
|
|||
|
```typescript
|
|||
|
import fs from 'fs';
|
|||
|
import path from 'path';
|
|||
|
|
|||
|
const contentDir = path.join(process.cwd(), 'content');
|
|||
|
|
|||
|
fs.readdir(contentDir, (err, files) => {
|
|||
|
if (err) throw err;
|
|||
|
|
|||
|
files.forEach(file => {
|
|||
|
const filePath = path.join(contentDir, file);
|
|||
|
fs.readFile(filePath, 'utf8', (err, data) => {
|
|||
|
if (err) throw err;
|
|||
|
|
|||
|
const smartfmInstance = new Smartfm({ fmType: 'yaml' });
|
|||
|
const parsedPage = smartfmInstance.parse(data);
|
|||
|
|
|||
|
console.log('Page Title:', parsedPage.data.title);
|
|||
|
console.log('Markdown Content:', parsedPage.content);
|
|||
|
|
|||
|
// Optionally, modify and update frontmatter
|
|||
|
parsedPage.data.title = 'Updated Title';
|
|||
|
const updatedContent = smartfmInstance.stringify(parsedPage.content, parsedPage.data);
|
|||
|
|
|||
|
fs.writeFile(filePath, updatedContent, (err) => {
|
|||
|
if (err) throw err;
|
|||
|
console.log('File updated successfully.');
|
|||
|
});
|
|||
|
});
|
|||
|
});
|
|||
|
});
|
|||
|
```
|
|||
|
|
|||
|
In this example, we read all markdown files from a directory, parse them to extract frontmatter data, optionally modify the frontmatter, and write the updated content back to the files.
|
|||
|
|
|||
|
### Advanced Use Cases
|
|||
|
|
|||
|
`@push.rocks/smartfm` is flexible enough to support advanced operations like validating frontmatter, applying transformations, and more. Here are a few ideas to explore:
|
|||
|
|
|||
|
#### Frontmatter Validation
|
|||
|
|
|||
|
You might want to validate the structure of frontmatter data against a schema before processing. Here's a conceptual idea using `@push.rocks/smartfm`:
|
|||
|
|
|||
|
```typescript
|
|||
|
import Ajv from 'ajv';
|
|||
|
|
|||
|
const ajv = new Ajv();
|
|||
|
const schema = {
|
|||
|
type: 'object',
|
|||
|
properties: {
|
|||
|
title: { type: 'string' },
|
|||
|
date: { type: 'string', format: 'date' }
|
|||
|
},
|
|||
|
required: ['title', 'date']
|
|||
|
};
|
|||
|
|
|||
|
const validate = ajv.compile(schema);
|
|||
|
|
|||
|
const frontmatter = smartfm.parse(sampleString).data;
|
|||
|
if (validate(frontmatter)) {
|
|||
|
console.log('Frontmatter is valid.');
|
|||
|
} else {
|
|||
|
console.error('Frontmatter validation failed:', validate.errors);
|
|||
|
}
|
|||
|
```
|
|||
|
|
|||
|
Using a validation library like Ajv, you can ensure that the parsed frontmatter adheres to a required schema or format, enhancing data integrity in larger applications.
|
|||
|
|
|||
|
#### Transformed Output
|
|||
|
|
|||
|
Suppose you want to output the parsed markdown content in a transformed format, such as HTML. Here’s how you could integrate a markdown parsing library:
|
|||
|
|
|||
|
```typescript
|
|||
|
import marked from 'marked';
|
|||
|
|
|||
|
const parsedResult = smartfm.parse(sampleString);
|
|||
|
const htmlContent = marked(parsedResult.content);
|
|||
|
|
|||
|
console.log('HTML Content:', htmlContent);
|
|||
|
```
|
|||
|
|
|||
|
By combining `@push.rocks/smartfm` with a markdown parsing library like `marked`, you can convert markdown content into other formats while handling the associated frontmatter.
|
|||
|
|
|||
|
With these examples, you can see how `@push.rocks/smartfm` fits into various workflows involving frontmatter and text processing. The module's simplicity and effectiveness make it a suitable choice for projects that require clean handling of document metadata.
|
|||
|
|
|||
|
Feel free to explore and extend these examples based on your particular use case. Whether you are building a simple script, a web application, or an extensive content management system, `@push.rocks/smartfm` provides a robust foundation for frontmatter operations. Happy coding!
|
|||
|
|
|||
|
## License and Legal Information
|
|||
|
|
|||
|
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
|
|||
|
|
|||
|
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
|
|||
|
|
|||
|
### Trademarks
|
|||
|
|
|||
|
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
|
|||
|
|
|||
|
### Company Information
|
|||
|
|
|||
|
Task Venture Capital GmbH
|
|||
|
Registered at District court Bremen HRB 35230 HB, Germany
|
|||
|
|
|||
|
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
|
|||
|
|
|||
|
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|