{"id":26021255,"url":"https://github.com/teclone/r-server","last_synced_at":"2025-03-06T08:50:39.621Z","repository":{"id":38175436,"uuid":"140939966","full_name":"teclone/r-server","owner":"teclone","description":"NodeJS production ready web-server with inbuilt routing-engine, static file server, file upload handler, request body parser, middleware support and lots more","archived":false,"fork":false,"pushed_at":"2024-02-11T17:50:43.000Z","size":60083,"stargazers_count":11,"open_issues_count":13,"forks_count":1,"subscribers_count":1,"default_branch":"master","last_synced_at":"2024-05-13T02:20:29.659Z","etag":null,"topics":["body-parser","cache-manager","middleware","rest-api","routing-engine","static-file-server","web-server"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/teclone.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-07-14T11:17:15.000Z","updated_at":"2024-02-28T06:51:03.000Z","dependencies_parsed_at":"2024-12-27T20:33:54.774Z","dependency_job_id":null,"html_url":"https://github.com/teclone/r-server","commit_stats":null,"previous_names":["harrison-ifeanyichukwu/r-server"],"tags_count":41,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/teclone%2Fr-server","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/teclone%2Fr-server/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/teclone%2Fr-server/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/teclone%2Fr-server/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/teclone","download_url":"https://codeload.github.com/teclone/r-server/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":242179280,"owners_count":20084940,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["body-parser","cache-manager","middleware","rest-api","routing-engine","static-file-server","web-server"],"created_at":"2025-03-06T08:50:38.874Z","updated_at":"2025-03-06T08:50:39.607Z","avatar_url":"https://github.com/teclone.png","language":"TypeScript","readme":"# R-Server\n\n[![Build Status](https://travis-ci.org/teclone/r-server.svg?branch=master)](https://travis-ci.org/teclone/r-server)\n[![Coverage Status](https://coveralls.io/repos/github/teclone/r-server/badge.svg?branch=master)](https://coveralls.io/github/teclone/r-server?branch=master)\n[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)\n[![npm version](https://badge.fury.io/js/r-server.svg)](https://badge.fury.io/js/%40teclone%2Fr-server)\n![npm](https://img.shields.io/npm/dt/%40teclone%2Fr-server.svg)\n\nRServer is a functional NodeJS web server, optimized for development and production needs, with inbuilt **routing engine**, **request body parser**, **static file streaming with range request support**, **file-upload-processing**, **middleware support**, **request-response profiler **, **excellent exception handling**, **error logging**, **Https easy setup** and lots more.\n\nRServer is compatible with Node v8.12 upwards and provides Http2 support out of the box.\n\n## Newly Added Features\n\n- Http2 support\n- Improved Server configuration file\n\n## Getting Started (NPM install)\n\n```bash\nnpm install @teclone/r-server\n```\n\n### Easily serve public folder\n\n```bash\nyarn r-sever serve\n```\n\n### Easily start a server (server.js)\n\n```typescript\n//create server.js\nconst { Server } = require('@teclone/r-server'); // import rserver\nconst server = new Server(); // create server instance\n\n// add some route\nserver.get('/', (req, res) =\u003e {\n  return res.end('Hello from RServer');\n});\n\n// export server to run it via cli (Recommended).\nmodule.exports = server;\n\n// or start the server by yourself\nserver.listen(3000).then(() =\u003e console.log('Running and ready'));\n```\n\nstart server via cli (Recommended)\n\n```bash\nyarn r-server start\n```\n\n## Features\n\nR-Server provides many excellent features out of the box. These include:\n\n2. [Configurability](#configuring-rserver)\n\n1. [Http2 Support](#http2)\n\n1. [Excellent Request Body Parser](#request-body-parser)\n\n1. [Excellent Routing Engine](#routing-engine)\n\n1. [Static File Server](#static-file-server)\n\n1. [Middleware Support](#middleware-support)\n\n1. [Mountable Router](#mountable-router)\n\n1. [Error Handling \u0026 Logging](#error-handling-\u0026-reporting)\n\n1. [Response Utility Methods](#response-utility-methods)\n\n1. [Custom Http Error Documents](#custom-http-error-documents)\n\n1. [HTTPS Support](#https-support)\n\n1. [Range Request Support](#range-request-support)\n\n### Configurability (.server.config.js)\n\nTo configure the server for advanced usage, create a `.server.config.js` as shown below. The configuration shown below is a sample configuration.\n\n```javascript\nconst { createConfig } = require('@teclone/rollup-all');\nmodule.exports = createConfig({\n  // file to log server errors\n  errorLog: 'logs/error.log',\n\n  // file to log client requests\n  accessLog: 'logs/access.log',\n\n  // folder to store file uploads\n  tempDir: 'tmp/uploads',\n\n  // public folders\n  publicPaths: ['public'],\n\n  // default assets cache control header\n  cacheControl: 'no-cache, max-age=86400',\n\n  encoding: 'latin1',\n\n  maxMemory: '50mb',\n\n  defaultDocuments: ['index.html', 'index.js', 'index.css'],\n\n  httpErrors: {\n    baseDir: '',\n    404: '',\n    500: '',\n  },\n\n  port: 8000,\n\n  https: {\n    enabled: false,\n\n    port: 9000,\n\n    /* enforce https by redirecting all http request to https */\n    enforce: false,\n\n    /* http version, default is http2 .*/\n    version: '2', //  Nodejs http2 implementation supports https/1 clients by default\n\n    /* https credentials, use  */\n    credentials: {\n      key: '.cert/server.key',\n      cert: '.cert/server.crt',\n      passphrase: 'pfx passphrase',\n    },\n  },\n});\n```\n\n### Http2 Support\n\nRServer supports http2 connection out of the box. Http2 is supported only on secure connections. Http2 is used by default if `https.enabled` is set to `true`. To use Https 1, set `https.version` to `1`\n\nIf `https.enforce` is set to true, the server listens for both http and https requests but will redirect all http requests to their equivalent https path.\n\nIf `https.enabled` is false, the server will listen for http only requests.\n\n### Request Body Parser\n\nIt comes with an inbuilt **request body parser**, that supports all forms of http request data such as **urlencoded query strings**, **application/json data**, **application/x-www-form-urlencoded data** and **multipart/form-data**.\n\nParsed fields and files are made available on the request object via the `data` properties. `request.data` contains parsed query string and parsed body. Fields from the query string are overwritten by fields in the response body.\n\n`request.query` contains the parsed query parameters.\n\nMulti-value fields are supported. They are recognised if the field name ends with the bracket notation `[]`. Note that the brackets are stripped out during the parsing.\n\n```typescript\nconst { Server } = require('@teclone/r-server'); // import rserver\nconst server = new Server(); // create server instance\n\nserver.put('users/{userId}/profile-picture', (req, res) =\u003e {\n  const picture = req.data.picture;\n\n  return res.json({\n    status: 'success',\n    message: 'got your file',\n    fileSize: picture.size,\n    mimeType: picture.type,\n    filename: picture.name,\n    bufferData: picture.data,\n  });\n});\n\nserver.listen().then(() =\u003e console.log('listening'));\n```\n\n### Routing Engine\n\nIt provides an excellent routing engine, with parameter capturing and can incorporate data type enforcement on captured parameters. All http method verbs are made available in the router including `get`, `post`, `put`, `delete`, `options`, `head` and an `all` method.\n\nParameter capturing sections are enclosed in curly braces `{}`;\n\nChanged routes are supported through the `Router#route(url)` method. Route callbacks and Middlewares are asynchronous in nature.\n\nIt also allows you to set route base path that gets prepended to all routes and middlewares.\n\n**Note that route urls can only be string patterns, and not regex objects**.\n\n**Usage Example**:\n\n```typescript\nconst { Server, Router } = require('@teclone/r-server'); // import rserver\nconst server = new Server(); // create server instance\n\n/** get route */\nserver.get(url, callback, options);\n\n/** post route */\nserver.post(url, callback, options);\n\n/** put route */\nserver.put(url, callback, options);\n\n/** head route */\nserver.head(url, callback, options);\n\n/** delete route */\nserver.delete(url, callback, options);\n\n/** options route */\nserver.options(url, callback, options);\n\n/** all method route */\nserver.all(url, callback, options);\n```\n\n**Data Type Enforcement on Captured Parameter**:\n\n```typescript\n//no data type enforcement\nserver.get('users/{userId}', (req, res, { userId }) =\u003e {\n  userId = /^\\d+$/.test(userId) ? Number.parseInt(userId) : 0;\n  if (userId !== 0) {\n    return res.status(200).json({\n      data: {\n        id: userId,\n        name: 'User Name',\n      },\n    });\n  } else {\n    return res.status(400).json({\n      errors: {\n        userId: 'user id not recognised',\n      },\n    });\n  }\n});\n\n//enforce data type\nserver.get('users/{int:userId}', (req, res, { userId }) =\u003e {\n  if (userId !== 0) {\n    return res.status(200).json({\n      data: {\n        id: userId,\n        name: 'User Name',\n      },\n    });\n  } else {\n    return res.status(400).json({\n      errors: {\n        userId: 'user id not recognised',\n      },\n    });\n  }\n});\n```\n\n**Chained Routes**:\n\n```typescript\nconst { Server } = require('@teclone/r-server'); // import rserver\nconst server = new Server(); // create server instance\n\nserver.route('users/{int:userId}')\n\n    .put((req, res, params) =\u003e {\n        //update user profile\n    });\n\n    .delete((req, res, {userId}) =\u003e {\n        //delete user\n    });\n\n    .get((req, res, {userId}) =\u003e {\n        //retrieve user\n    });\n```\n\n### Route Base Path\n\nIt provides api for setting routing base path that gets prepended to all route urls and middleware urls. This is very helpful when exposing versioned api endpoints in your applications.\n\n**NB: Route base path must be set before registering routes.**\n\n```typescript\n\nconst { Server } = require('@teclone/r-server'); // import rserver\nconst server = new Server(); // create server instance\n\n//examples\nserver.setBasePath('api/v2.0');\n\n//this route will be called when post request is made on the endpoint /api/v2.0/auth\nserver.post('auth', (req, res)=\u003e {\n    return res.end('received');\n}));\n```\n\n### Static File Server\n\nRserver supports streaming/serving of public static files of the box, responding to **GET**, **HEAD**, \u0026 **OPTIONS** requests made on such static files. By default, it serves files from the `./public` folder, but this can be extended or changed.\n\nThe list of Default documents includes `index.html`, `index.css`, `index.js`. See [configuring-rserver](#configuring-rserver) on how to configure the list of default documents and so many other options.\n\nIt uses NodeJS inbuilt [writable \u0026 readable stream API](https://nodejs.org/api/stream.html#stream_class_stream_writable) while serving files for performance gain, user experience and minimal usage of system resources.\n\nIt provides content negotiation [headers](https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html) (`Cache-Control`, `ETag` \u0026 `Last-Modified`) and would negotiate contents by checking for the presence of the `if-none-match`, `if-modified-since`, \u0026 the `if-range` http request headers.\n\n### Middleware Support\n\nIt supports the use of middlewares making it easy to run security or pluggable modules per request. One can register global/standalone middlewares or localized route based middlewares. Middlewares can be a single or an array of javascript functions. Middlewares can be asynchronous functions too, that return promises.\n\n```typescript\nconst { Server } = require('@teclone/r-server'); // import rserver\nconst server = new Server(); // create server instance\n\n//runs on all request paths, and methods\nserver.use('*', (req, res, next) =\u003e {\n  //check if auth token is present in the header and set the req.user property\n  return next(); //execute next to pass control to next middleware\n});\n\n//runs on root domain and only on post requests\nserver.use('/', (req, res, next) =\u003e next(), {method: 'post'};\n\n// runs on all request paths starting with users/{userId}, inclusive, and all methods\nserver.use('users/{userId}/*', (req, res, next, {userId}) =\u003e next());\n\n//route localized middleware\nserver.get('auth/login', (req, res) =\u003e {\n  return res.end('login form will be served :)');\n}, (req, res, next) =\u003e {\n  //redirect user to homepage if user is logged in\n  if (req.user) {\n      return res.redirect('/');\n  }\n  else {\n      return next();\n  }\n});\n\n// or\nserver.get('auth/login', (req, res) =\u003e {\n  return res.end('login form will be served :)');\n}, {\n    use: [\n      (req, res, next) =\u003e {\n        //redirect user to homepage if user is logged in\n        if (req.user) {\n            return res.redirect('/');\n        }\n        else {\n            return next();\n        }\n      },\n\n      // ...more middlewares if you like\n    ]\n  }\n});\n```\n\n### Mountable Router\n\nMountable router are standalone router instances that can be mounted on the main server. Mountable routers can inherit the main app's standalone middlewares.\n\n**File routes/AuthRoutes.ts**:\n\n```typescript\nconst { Router } = require('@teclone/r-server'); // import rserver\nconst authRoutes = new Router(true); // create a mountable router, inherit middleware options is set as true.\n\n//define specific middlewares for auth\nauthRoutes.use('*', (req, res, next) =\u003e {\n  // if user is logged in, redirect to homepage\n  if (req.user) {\n    return res.redirect('/');\n  } else {\n    return next();\n  }\n});\n\nauthRoutes.post('signup', (req, res) =\u003e {\n  // process account creation\n});\n\nauthRoutes.post('login', (req, res) =\u003e {\n  //process login\n});\n\nauthRoutes.post('reset-password', (req, res) =\u003e {\n  // process password reset\n});\n\nexport default Authroutes;\n```\n\n**File server.ts**:\n\n```typescript\nconst { App } = require('@teclone/r-server');\nconst authRoutes = require('./routes/authRoutes');\n\nconst server = RServer.create();\n\nserver.get('/', (req, res) =\u003e {\n  return res.end('Welcome');\n});\n\nserver.mount('/auth', authRoutes);\n\nserver.listen().then(() =\u003e console.log('listening'));\n```\n\n### Error Handling \u0026 Reporting\n\nIt logs errors to a user defined error log file which defaults to **logs/error.log**.\nWhen running in development mode, it sends error message and traces back to the client (browsers, etc). In production mode, it hides the error message from the client, but still logs the error to the error log file.\n\nBy design, route callbacks are made to return promises, this helps bubble up any error up to our internal error handler for the event loop.\n\n### Response Utility Methods\n\nThere are some extended methods made available on the Response object, that includes the following:\n\n```typescript\n\n/**\n * ends the response with optional response data, and optional data encoding\n */\nend(data?, encoding?: string): Promise\u003cboolean\u003e;\n\n/**\n * sets response header\n */\nsetHeader(name: string, value: string | number | string[]): this;\n\n/**\n * sets multiple response headers\n */\nsetHeaders(headers: {[p: string]: string | number | string[]}): this;\n\n/**\n * removes a single set response header at a time. function is chainable\n */\nremoveHeader(name: string): this;\n\n/**\n * remove response headers that are already set. function is chainable\n */\nremoveHeaders(...names: string[]): this;\n\n/**\n * sets response status code\n */\nstatus(code: number): this;\n\n/**\n * sends json response back to the client.\n */\njson(data: object | string): Promise\u003cboolean\u003e;\n\n/**\n * Redirect client to the given url\n */\nredirect(path: string, status: number = 302): Promise\u003cboolean\u003e;\n\n/**\n * sends a file download attachment to the client\n */\ndownload(filePath: string, filename?: string): Promise\u003cboolean\u003e;\n```\n\n### Custom HTTP Error Documents\n\nRServer allows the ability to define custom http error files that are mapped to http error codes such as [404](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404), etc. This is achieved by defining a `httpErrors` entry in your config file. See [Configuring RServer](#configuring-rserver) for details.\n\n### Range Request Support\n\nRServer will automatically detect and handle any [byte-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests) requests that hits the server. This is very important when serving large files such as video and audio files. Range requests is used for data buffering. Visit this [link to read more](https://tools.ietf.org/html/rfc7233) on range requests.\n\n## Contributing\n\nWe welcome your own contributions, ranging from code refactoring, documentation improvements, new feature implementations, bugs/issues reporting, etc. we recommend you follow the steps below to actively contribute to this project.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fteclone%2Fr-server","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fteclone%2Fr-server","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fteclone%2Fr-server/lists"}