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

express-fsr

v2.2.3

Published

Simple Pluggable File System Routing inspired by NuxtJS

Downloads

3

Readme

express-fsr

Simple Pluggable File System Routing for ExpressJS, inspired by NuxtJS's router.

version npm issues stars

Getting Started

Install express-fsr as a dependency:

$ yarn add express-fsr

Add the router to your existing Express app:

// src/index.js
const { createRouter } = require('express-fsr');
const path = require('path');

const routerOpts = {
  // point to your routes directory
  baseDir: path.join(__dirname, 'routes'),
};

const router = createRouter(routerOpts);
app.use('/', router);

Directory Structure

express-fsr reads all files inside your routes (or wherever you point it to) directory, and builds the route based on the file's path and applies the exported verb (const get, post, put, // etc...) as the handlers.

Router Config

| Field | Type | Description | Default | | ------------------ | ----------------- | ------------------------------------------------------------ | ----------- | | baseDir | string | Change the base directory to include. Path must be absolute. | /routes | | strictExports | boolean | Throw an error if a file exports an unknown variable. | false | | router | object | Options to pass to Express router. | undefined | | middlewares | function\|array | Middlewares to add to all router's routes. | undefined | | dirs | array | A string or regex array to test for allowed directories. | undefined | | excludeDirs | array | A string or regex array to test for excluded directories. | undefined | | includeRootFiles | boolean | Include files inside the root directory. | true |

Sample Routes

├── routes/
│   ├── users/
│   │   └── _id/
│   │       ├── index.js
│   │       └── data.js
│   └── index.js

Sample Handlers

Important: delete method is aliased as del, since delete is a reserved keyword.

// src/routes/index.js
// GET /
const get = (req, res) => {
  res.json({ message: 'Hello world!' });
}

module.exports = { get };
// src/routes/users/_id/index.js
// GET /users/:id
const get = (req, res) => {
  res.json({ userId: req.params.id });
}

// DELETE /users/:id
const del = (req, res) => {
  res.json({ userId: req.params.id, deleted: 1 });
}

module.exports = { get, del };
// src/routes/users/_id/data.js
// GET /users/:id/data
const get = (req, res) => {
  res.json({ userId: req.params.id, name: 'foo' });
}

// POST /users/:id/data
const post = (req, res) => {
  res.json({ userId: req.params.id, ok: 1 });
}

module.exports = { get, post };

Middlewares

express-fsr grabs middlewares from an exported variable middlewares.

Usage

// Per-router middleware
const { createRouter } = require('express-fsr');

const middlewares;
const router = createRouter({ middlewares });

// Per-file middleware
const middlewares;
module.exports = { middlewares };

Per-file middlewares

// single middleware
const middlewares = async (req, res, next) => {
  console.log('this route was called!');
  next();
};

// multiple middlewares
const middlewares = [
  myMiddleware1,
  myMiddleware2,
];

Per-handler middlewares

// single/multiple middlewares
const middlewares = {
  async get(req, res, next) {
    console.log('get handler was called!');
    next();
  },
  post: [myAuthMiddleware, async (req, res, next) => {
    console.log('post handler authenticated!')
    next();
  }],
}

Advanced Usage

Router composition

You can include/exclude directories with each router, allowing you to easily compose multiple routes with custom middlewares.

const { Router } = require('express');
const { createRouter } = require('express-fsr');

// Base router where we attach our actual routes
const baseRouter = Router();

// Router where we add auth middlewares
const authRouter = createRouter({
  // Only add routes inside /routes/auth/*
  includeDirs: ['auth'],
  // Attach our auth middlewares
  middlewares: async (req, res, next) => {
    // do authentication
    console.log('request authenticated!');
    next();
  },
});

// Router where any requests can go through
const publicRouter = createRouter({
  // Exclude our authenticated routes
  excludeDirs: ['auth'],
  // Optional: only enable if you have files like /routes/index.js
  includeRootFiles: true,
});

// Attach our routers to our base router
baseRouter.use(authRouter);
baseRouter.use(publicRouter);

// Use our router
app.use('/api', baseRouter);

Typescript

This package is written using Typescript, so types are supported out of the box!

// Interfaces
import { Middlewares, RouterOpts } from 'express-fsr';

const middlewares: Middlewares = [];
const routerOpts: RouterOpts = {};

// Handlers
import { Middlewares, RequestHandler } from 'express-fsr';

export const middleware: Middlewares = {
  async get(req, res, next) {
  }
}

export const get: RequestHandler = async (req, res, next) => {
};