Skip to content

Small router for node.js http/https

License

Notifications You must be signed in to change notification settings

mike1pol/node-router

Repository files navigation

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`)
})