Socket
Socket
Sign inDemoInstall

rjweb-server

Package Overview
Dependencies
2
Maintainers
1
Versions
369
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    rjweb-server

Easy and Lightweight Way to create a Web Server in Node.js


Version published
Weekly downloads
35
decreased by-69.03%
Maintainers
1
Created
Weekly downloads
Ā 

Readme

Source

Welcome to rjweb-server šŸ‘‹

Version Documentation Maintenance

Easy and Lightweight Way to create a Web Server in Node.js

šŸ  Homepage

Install

npm i rjweb-server

or

yarn add rjweb-server

Typescript

Importing

import * as webserver from "rjweb-server"

Interface for ctr Object

import { ctr } from "rjweb-server/interfaces"

const routes = new webserver.routeList()

routes.set(webserver.types.get, '/hello', async(ctr: ctr) => {
  if (!ctr.query.has("name")) return ctr.print('please supply the name query!!')

  return ctr.print(`Hello, ${ctr.query.get("name")}! How are you doing?`)
})

// ...

Usage

Initialize Server

const webserver = require('rjweb-server')
const routes = new webserver.routeList()

// ctr.query.get... is ?name=
routes.set(webserver.types.get, '/hello', async(ctr) => {
  if (!ctr.query.has("name")) return ctr.print('please supply the name query!!')

  return ctr.print(`Hello, ${ctr.query.get("name")}! How are you doing?`)
})

// ctr.param.get... is :name, example /hello/0x4096
routes.set(webserver.types.get, '/hello/:name', async(ctr) => {
  return ctr.print(`Hello, ${ctr.param.get("name")}! How are you doing?`)
})

// ctr.param.get... is :name, example /hello/0x4096
routes.set(webserver.types.post, '/post', async(ctr) => {
  return ctr.print(`Hello, ${ctr.reqBody}! How are you doing?`)
})

routes.set(webserver.types.get, '/profile/:user', async(ctr) => {
  ctr.setHeader('Content-Type', 'image/png')
  return ctr.printFile(`../images/profile/${ctr.param.get('user')}.png`)
})

webserver.start({
  bind: '0.0.0.0', // The IP thats bound to
  body: 20, // The Max POST Body in MB
  cors: false, // If Cors Headers will be added
  port: 5000, // The Port which the Server runs on
  urls: routes, // The Routes Object
  proxy: true // If enabled, alternate IPs will be shown
}).then((res) => {
  console.log(`webserver started on port ${res.port}`)
})

Serve Static Files

const webserver = require('rjweb-server')
const routes = new webserver.routeList()

routes.static('/', './html', {
  preload: false, // If enabled will load every static files content into Memory
  remHTML: true // If enabled will remove the html ending from files when serving
}) // The html folder is in the root directory

webserver.start({
  bind: '0.0.0.0',
  cors: false,
  port: 5000,
  urls: routes,
  proxy: true
}).then((res) => {
  console.log(`webserver started on port ${res.port}`)
})

Custom 404 / 500 Page

webserver.start({
  bind: '0.0.0.0',
  cors: false,
  port: port,
  urls: routes,
  proxy: true,
  pages: {
    notFound: async(ctr) {
      ctr.status(404)
      return ctr.print(`page "${ctr.reqUrl.pathname}" not found`)
    }, reqError: async(ctr) => {
      ctr.status(500)
      ctr.print(`ERROR!!! ${ctr.error.message}`)
      return console.log(ctr.error)
    }
  }
}).then((res) => {
  console.log(`webserver started on port ${res.port}`)
})

Custom Function on every request

webserver.start({
  bind: '0.0.0.0',
  cors: false,
  port: port,
  urls: routes,
  proxy: true,
  events: {
    request: async(ctr) => {
      return console.log(`request made to ${decodeURI(ctr.reqUrl.pathname)} by ${ctr.hostIp}`) // DO NOT write any data or end the request
    }
  }
}).then((res) => {
  console.log(`webserver started on port ${res.port}`)
})

Rate Limits

With Database (EXAMPLE, PLEASE EDIT)

webserver.start({
  bind: '0.0.0.0',
  cors: false,
  port: port,
  urls: routes,
  proxy: true,
  rateLimits: {
    enabled: true,
    message: 'You are being rate limited',
    list: [
      {
        path: '/auth',
        times: 5,
        timeout: 10000
      },
      {
        path: '/fetch',
        times: 3,
        timeout: 5000
      }
    ], functions: {
      set: async(key, value) => (await db.query('update ratelimits set value = ? where key = ?;', [value, key])),
      get: async(key) => ((await db.query('select value from ratelimits where key = ?;', [key])).data.rows[0].value),
      del: async(key, value) => (await db.query('delete from ratelimits where key = ?;', [key]))
    }
  }
}).then((res) => {
  console.log(`webserver started on port ${res.port}`)
})

With Map

const rateLimits = new Map()

webserver.start({
  bind: '0.0.0.0',
  cors: false,
  port: port,
  urls: routes,
  proxy: true,
  rateLimits: {
    enabled: true,
    message: 'You are being rate limited',
    list: [
      {
        path: '/auth',
        times: 5,
        timeout: 10000
      },
      {
        path: '/fetch',
        times: 3,
        timeout: 5000
      }
    ], functions: rateLimits
  }
}).then((res) => {
  console.log(`webserver started on port ${res.port}`)
})

Cleaning Up Functions

Load Functions from Directory

const webserver = require('rjweb-server')
const routes = new webserver.routeList()

routes.load('./functions') // The functions folder is in the root directory

webserver.start({
  bind: '0.0.0.0',
  cors: false,
  port: 5000,
  urls: routes,
  proxy: true,
}).then((res) => {
  console.log(`webserver started on port ${res.port}`)
})

Making a function File

const webserver = require('rjweb-server')

// For Typescript just use `export =` instead
module.exports = {
  type: webserver.types.get,
  path: '/say/:word',

  async code(ctr) {
    const word = ctr.param.get('word')

    return ctr.print(`I will say it!!!\n${word}`)
  }
}

Full Example

https://replit.com/@RobertJansen/aous

Author

šŸ‘¤ 0x4096

šŸ¤ Contributing

Contributions, issues and feature requests are welcome!
Feel free to check issues page.

Show your support

Give a Star if this project helped you!

šŸ“ License

Copyright Ā© 2022 0x4096.
This project is ISC licensed.

Keywords

FAQs

Last updated on 06 Jan 2023

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with āš”ļø by Socket Inc