@mikepol/node-router

0.1.2 • Public • Published

Node-Router

Small router for node.js http/https

Build Status npm version codecov JavaScript Style Guide

Install

npm install @mikepol/node-router

Example

const http = require('http')
const router = require('@mikepol/node-router')
const routes = [
  {
    method: 'get',
    url: '/',
    handler: (req, res) => {
      res.statusCode = 200
      res.setHeader('Content-Type', 'text/plain')
      res.end('get /')
    }
  },
  {
    method: 'post',
    url: '/',
    handler: (req, res) => {
      res.statusCode = 200
      res.setHeader('Content-Type', 'text/plain')
      res.end('post /')
    }
  },
  {
    method: 'get',
    url: /^\/page\/(\d)/,
    handler: (req, res) => {
      console.log(req.route.match);
      res.statusCode = 200
      res.setHeader('Content-Type', 'text/plain')
      res.end('post /')
    }
  },
  {
    url: '/all',
    handler: (req, res) => {
      res.statusCode = 200
      res.setHeader('Content-Type', 'text/plain')
      res.end('/all')
    }
  },
  {
    notFound: true,
    handler: (req, res) => {
      res.statusCode = 404
      res.setHeader('Content-Type', 'text/plain')
      res.end('404 - Not found')
    }
  }
]

const srv = http.createServer(router(routes))
srv.listen(3000, (err) => {
  if (err) {
    console.error('server listen error:', err)
  }
  console.log(`server started on http://localhost:3000`)
})

Readme

Keywords

Package Sidebar

Install

npm i @mikepol/node-router

Weekly Downloads

0

Version

0.1.2

License

MIT

Unpacked Size

6.04 kB

Total Files

5

Last publish

Collaborators

  • mikepol