😎 Fast Async Web Framework For Modern Node.js
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
benchmarks
examples
lib
test
.gitignore
.travis.yml
LICENSE
README.md
package-lock.json
package.json

README.md

Trek

Trek.js

Fast Async Web Framework For Modern Node.js

Build status Codecov NPM version Styled with prettier MIT License

Features

  • Elegant. Use async and await for asynchronous programs

  • Fast. High performance middleware and router

  • Modern. ES6+, only for Node.js v8+

  • Flexible. Modular and extensible

  • Amiable. Similar to Express.js and Koa.js

Installation

$ npm install trek --save

Examples

Hello Trek

The lightweight app uses with Engine. Likes Koa.

const { Engine: Trek, Router } = require('../../lib')

async function launch() {
  const app = new Trek()

  const router = new Router()

  router.add('GET', '/', async ({ res }) => {
    res.send(200, 'Hello, Trek!')
  })

  router.add('GET', '/startrek', async ({ res }) => {
    res.type = 'html'
    res.send(200, Buffer.from('Hello, Star Trek!'))
  })

  router.add('POST', '/', async ({ res }) => {
    res.send(200, {
      status: 'ok',
      message: 'success'
    })
  })

  app.use(async ({ req, res }, next) => {
    const start = new Date()
    await next()
    const ms = new Date() - start
    console.log(`${ms}ms`)
  })

  app.use(async ({ req, res }, next) => {
    const route = router.find(req.method, req.path)
    if (route) {
      const [handler] = route
      if (handler !== undefined) {
        await handler({ req, res })
        return
      }
    }
    await next()
  })

  app.use(async ({ res }) => {
    res.status = 404
    res.end()
  })

  app.run(3000)
}

launch().catch(console.error)

Star Trek

The richer app, customize and expand your app.

const Trek = require('../../lib')

async function launch() {
  const app = new Trek()

  app.paths.set('app', { single: true })
  app.paths.set('app/plugins', { glob: 'app/plugins/index.js', single: true })
  app.paths.set('app/controllers', { glob: 'app/controllers/*.js' })

  await app.bootUp()

  app.use(async ({ logger, rawReq, rawRes }, next) => {
    logger.info(rawReq)
    await next()
    logger.info(rawRes)
  })

  app.use(async ({ cookies }, next) => {
    cookies.set('name', 'trek')
    await next()
  })

  app.use(ctx => {
    if (ctx.req.path === '/') {
      return ctx.res.send(200, 'Star Trek!')
    } else if (ctx.req.path === '/error') {
      throw new Error('Nothing')
    }
    // Something else return 404
    ctx.cookies.set('name', null)
    ctx.res.send(404)
  })

  app.on('error', err => {
    app.logger.error(err)
  })

  await app.run(3000)
}

launch().catch(console.error)

fundon.me  ·  GitHub @fundon  ·  Twitter @_fundon