0.3.1 • Published 3 years ago

express-fs-autorouter v0.3.1

Weekly downloads
-
License
-
Repository
github
Last release
3 years ago

express-fs-autorouter

File-based auto routing for Express

Given a project directory of .js files like the following:

/project
└── api
    ├── index.js
    ├── login.js
    └── accounts
        └── index.js

Passing the api directory to express-fs-autorouter will create an Express router to automatically map URL paths to corresponding files:

/           =>  api/index.js
/login      =>  api/login.js
/accounts/  =>  api/accounts/index.js

Installation

yarn add express-fs-autorouter
# OR
npm install express-fs-autorouter

Usage

In your Express app, use autoRouter(), passing in an absolute path to the directory to search for .js handler files. (If you pass no path, it will use process.cwd().)

const { resolve } = require("path");
const express = require("express");
const autoRouter = require("express-fs-autorouter");

const app = express();

// auto-routing
const apiDir = resolve(__dirname, "api");
app.use(autoRouter(apiDir));

// start server
app.listen(8080);

In each handler file, export a connect-/Express-style handler function:

module.exports = (req, res) => {
  res.send("Hello, World!");
};

You can also export an express() instance, which has the same (req, res, next) signature:

const express = require("express");

const handler = express();
module.exports = handler;

handler
  .route("*")
  .get((req, res) => {
    res.send("Hello, World!");
  });
0.3.0

3 years ago

0.2.0

3 years ago

0.3.1

3 years ago

0.1.2

3 years ago

0.1.1

3 years ago

0.1.0

3 years ago