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

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

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:

  1. Go to GitHub Token Settings.
  2. Click Generate new token (classic).
  3. Select the repo scope.
  4. 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

  1. Go to your repository on GitHub.
  2. Navigate to Settings > Secrets and variables > Actions.
  3. Click New repository secret.
  4. Add a new secret:
    • Name: GITHUB_TOKEN
    • Value: Paste your personal access token (PAT).

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! 🚀