gh-pages-fs
v1.1.1
Published
A TypeScript package to read and write JSON files to the gh-pages branch using the GitHub API.
Downloads
131
Maintainers
Readme
gh-pages-fs
gh-pages-fs
is a lightweight utility for managing JSON files in a GitHub repository's gh-pages
branch. It simplifies reading, writing, and updating JSON files using the GitHub API, making it easy to store and retrieve user-generated data or configurations directly in your GitHub repository.
Features
- Read JSON Files: Retrieve JSON content from a specific file in the
gh-pages
branch. - Write JSON Files: Create or update JSON files with new content.
- Automatic File Creation: Automatically creates a JSON file with an empty object if the file does not exist.
Installation
Install the package via npm:
npm install gh-pages-fs
Usage
Initialization
Create an instance of the GhPagesFS
class by providing your GitHub repository details:
import { GhPagesFS } from 'gh-pages-fs';
const ghPagesFs = new GhPagesFS({
owner: 'your-github-username',
repo: 'your-repo-name',
branch: 'gh-pages', // Optional, defaults to 'gh-pages'
token: 'your-github-token' // Required, generate from GitHub with repo access
});
Read a JSON File
Retrieve the content of a JSON file from the gh-pages
branch. If the file does not exist, it will automatically create one with an empty object.
const filePath = 'data/example.json';
async function readData() {
try {
const jsonData = await ghPagesFs.readJson(filePath);
console.log('File content:', jsonData);
} catch (error) {
console.error('Error reading JSON file:', error);
}
}
readData();
Write to a JSON File
Update or create a JSON file in the gh-pages
branch with new content.
const filePath = 'data/example.json';
const newData = { key: 'value' };
async function writeData() {
try {
await ghPagesFs.writeJson({
filePath,
jsonData: newData,
commitMessage: 'Update example JSON file'
});
console.log('File updated successfully.');
} catch (error) {
console.error('Error writing JSON file:', error);
}
}
writeData();
Example: Save and Retrieve User Data
Save and retrieve user test results stored in a user_test_results.json
file.
const filePath = 'user_test_results.json';
// Save user data
async function saveTestResult(userId: string, resultData: Record<string, any>) {
try {
const jsonData = await ghPagesFs.readJson(filePath);
jsonData[userId] = resultData; // Add or update user test result
await ghPagesFs.writeJson({
filePath,
jsonData,
commitMessage: `Save test results for user ${userId}`
});
console.log(`Test result for user ${userId} saved successfully.`);
} catch (error) {
console.error(`Failed to save test result: ${error}`);
}
}
// Retrieve user data
async function retrieveTestResult(userId: string) {
try {
const jsonData = await ghPagesFs.readJson(filePath);
console.log('User data:', jsonData[userId] || 'No data found');
} catch (error) {
console.error(`Failed to retrieve test result: ${error}`);
}
}
const userId = 'user123';
const resultData = { score: 95, type: 'INTJ' };
saveTestResult(userId, resultData);
retrieveTestResult(userId);
Configuration
Parameters
| Parameter | Type | Required | Default | Description |
|-----------|----------|----------|--------------|-----------------------------------------------------------|
| owner
| string
| Yes | N/A | The GitHub username or organization name. |
| repo
| string
| Yes | N/A | The GitHub repository name. |
| branch
| string
| No | gh-pages
| The branch where the file resides (e.g., gh-pages
). |
| token
| string
| Yes | N/A | GitHub Personal Access Token with repo
scope. |
GitHub Personal Access Token
To use this package, you must generate a Personal Access Token (PAT) with appropriate permissions:
- Go to GitHub Token Settings.
- Click Generate new token (classic).
- Select the
repo
scope. - Copy the token and store it securely.
GitHub Secrets and Workflow Integration
For security, you should avoid hardcoding your GitHub token directly into the codebase. Instead, store it as a GitHub secret and access it in your CI/CD workflow.
Step 1: Add Your Token to GitHub Secrets
- Go to your repository on GitHub.
- Navigate to Settings > Secrets and variables > Actions.
- Click New repository secret.
- Add a new secret:
- Name:
GITHUB_TOKEN
- Value: Paste your personal access token (PAT).
- Name:
Step 2: Use the Token in a GitHub Actions Workflow
Here’s an example workflow file to use gh-pages-fs
in your GitHub Actions:
name: Update JSON File
on:
push:
branches:
- main
jobs:
update-json:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: 16
- name: Install Dependencies
run: npm install
- name: Update JSON File
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
node -e "
const { GhPagesFS } = require('./gh-pages-fs');
const fs = new GhPagesFS({
owner: 'your-github-username',
repo: 'your-repo-name',
branch: 'gh-pages',
token: process.env.GITHUB_TOKEN
});
(async () => {
await fs.writeJson({
filePath: 'data/example.json',
jsonData: { example: 'data' },
commitMessage: 'Update example JSON file via GitHub Actions'
});
})();
"
Replace your-github-username
and your-repo-name
with your repository details.
Error Handling
- If a file does not exist,
readJson
will automatically create it with an empty object. - Errors during API requests (e.g., network issues, invalid tokens) are thrown and should be caught using
try-catch
.
Compatibility
- Works in Node.js and browser environments.
- For browser usage, ensure the GitHub token is securely managed (e.g., via environment variables in a server-side implementation).
License
This package is licensed under the MIT License. See LICENSE for details.
Feel free to reach out with questions or contribute to the project! 🚀