RServer 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.
RServer is compatible with Node v8.12 upwards and provides Http2 support out of the box.
- Http2 support
- Improved Server configuration file
npm install @teclone/r-serveryarn r-sever serve//create server.jsconst{ Server }=require('@teclone/r-server');// import rserverconstserver=newServer();// create server instance// add some routeserver.get('/',(req,res)=>{returnres.end('Hello from RServer');});// export server to run it via cli (Recommended).module.exports=server;// or start the server by yourselfserver.listen(3000).then(()=>console.log('Running and ready'));start server via cli (Recommended)
yarn r-server startR-Server provides many excellent features out of the box. These include:
To configure the server for advanced usage, create a .server.config.js as shown below. The configuration shown below is a sample configuration.
const{ createConfig }=require('@teclone/rollup-all');module.exports=createConfig({// file to log server errorserrorLog: 'logs/error.log',// file to log client requestsaccessLog: 'logs/access.log',// folder to store file uploadstempDir: 'tmp/uploads',// public folderspublicPaths: ['public'],// default assets cache control headercacheControl: 'no-cache, max-age=86400',encoding: 'latin1',maxMemory: '50mb',defaultDocuments: ['index.html','index.js','index.css'],httpErrors: {baseDir: '',404: '',500: '',},port: 8000,https: {enabled: false,port: 9000,/* enforce https by redirecting all http request to https */enforce: false,/* http version, default is http2 .*/version: '2',// Nodejs http2 implementation supports https/1 clients by default/* https credentials, use */credentials: {key: '.cert/server.key',cert: '.cert/server.crt',passphrase: 'pfx passphrase',},},});RServer 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
If 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.
If https.enabled is false, the server will listen for http only requests.
It 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.
Parsed 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.
request.query contains the parsed query parameters.
Multi-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.
const{ Server }=require('@teclone/r-server');// import rserverconstserver=newServer();// create server instanceserver.put('users/{userId}/profile-picture',(req,res)=>{constpicture=req.data.picture;returnres.json({status: 'success',message: 'got your file',fileSize: picture.size,mimeType: picture.type,filename: picture.name,bufferData: picture.data,});});server.listen().then(()=>console.log('listening'));It 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.
Parameter capturing sections are enclosed in curly braces {};
Changed routes are supported through the Router#route(url) method. Route callbacks and Middlewares are asynchronous in nature.
It also allows you to set route base path that gets prepended to all routes and middlewares.
Note that route urls can only be string patterns, and not regex objects.
Usage Example:
const{ Server, Router }=require('@teclone/r-server');// import rserverconstserver=newServer();// create server instance/** get route */server.get(url,callback,options);/** post route */server.post(url,callback,options);/** put route */server.put(url,callback,options);/** head route */server.head(url,callback,options);/** delete route */server.delete(url,callback,options);/** options route */server.options(url,callback,options);/** all method route */server.all(url,callback,options);Data Type Enforcement on Captured Parameter:
//no data type enforcementserver.get('users/{userId}',(req,res,{ userId })=>{userId=/^\d+$/.test(userId) ? Number.parseInt(userId) : 0;if(userId!==0){returnres.status(200).json({data: {id: userId,name: 'User Name',},});}else{returnres.status(400).json({errors: {userId: 'user id not recognised',},});}});//enforce data typeserver.get('users/{int:userId}',(req,res,{ userId })=>{if(userId!==0){returnres.status(200).json({data: {id: userId,name: 'User Name',},});}else{returnres.status(400).json({errors: {userId: 'user id not recognised',},});}});Chained Routes:
const{ Server }=require('@teclone/r-server');// import rserverconstserver=newServer();// create server instanceserver.route('users/{int:userId}').put((req,res,params)=>{//update user profile});.delete((req,res,{userId})=>{//delete user});.get((req,res,{userId})=>{//retrieve user});It 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.
NB: Route base path must be set before registering routes.
const{ Server }=require('@teclone/r-server');// import rserverconstserver=newServer();// create server instance//examplesserver.setBasePath('api/v2.0');//this route will be called when post request is made on the endpoint /api/v2.0/authserver.post('auth',(req,res)=>{returnres.end('received');}));Rserver supports streaming/serving of public static files of the box, responding to GET, HEAD, & OPTIONS requests made on such static files. By default, it serves files from the ./public folder, but this can be extended or changed.
The list of Default documents includes index.html, index.css, index.js. See configuring-rserver on how to configure the list of default documents and so many other options.
It uses NodeJS inbuilt writable & readable stream API while serving files for performance gain, user experience and minimal usage of system resources.
It provides content negotiation headers (Cache-Control, ETag & Last-Modified) and would negotiate contents by checking for the presence of the if-none-match, if-modified-since, & the if-range http request headers.
It 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.
const{ Server }=require('@teclone/r-server');// import rserverconstserver=newServer();// create server instance//runs on all request paths, and methodsserver.use('*',(req,res,next)=>{//check if auth token is present in the header and set the req.user propertyreturnnext();//execute next to pass control to next middleware});//runs on root domain and only on post requestsserver.use('/',(req,res,next)=>next(),{method: 'post'};// runs on all request paths starting with users/{userId}, inclusive, and all methodsserver.use('users/{userId}/*',(req,res,next,{userId})=>next());//route localized middlewareserver.get('auth/login',(req,res)=>{returnres.end('login form will be served :)');},(req,res,next)=>{//redirect user to homepage if user is logged inif(req.user){returnres.redirect('/');}else{returnnext();}});// orserver.get('auth/login',(req,res)=>{returnres.end('login form will be served :)');},{use: [(req,res,next)=>{//redirect user to homepage if user is logged inif(req.user){returnres.redirect('/');}else{returnnext();}},// ...more middlewares if you like]}});Mountable router are standalone router instances that can be mounted on the main server. Mountable routers can inherit the main app's standalone middlewares.
File routes/AuthRoutes.ts:
const{ Router }=require('@teclone/r-server');// import rserverconstauthRoutes=newRouter(true);// create a mountable router, inherit middleware options is set as true.//define specific middlewares for authauthRoutes.use('*',(req,res,next)=>{// if user is logged in, redirect to homepageif(req.user){returnres.redirect('/');}else{returnnext();}});authRoutes.post('signup',(req,res)=>{// process account creation});authRoutes.post('login',(req,res)=>{//process login});authRoutes.post('reset-password',(req,res)=>{// process password reset});exportdefaultAuthroutes;File server.ts:
const{ App }=require('@teclone/r-server');constauthRoutes=require('./routes/authRoutes');constserver=RServer.create();server.get('/',(req,res)=>{returnres.end('Welcome');});server.mount('/auth',authRoutes);server.listen().then(()=>console.log('listening'));It logs errors to a user defined error log file which defaults to logs/error.log. When 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.
By design, route callbacks are made to return promises, this helps bubble up any error up to our internal error handler for the event loop.
There are some extended methods made available on the Response object, that includes the following:
/** * ends the response with optional response data, and optional data encoding */end(data?,encoding?: string): Promise<boolean>;/** * sets response header */setHeader(name: string,value: string|number|string[]): this;/** * sets multiple response headers */setHeaders(headers: {[p: string]: string |number|string[]}): this;/** * removes a single set response header at a time. function is chainable */removeHeader(name: string): this;/** * remove response headers that are already set. function is chainable */removeHeaders(...names: string[]): this;/** * sets response status code */status(code: number): this;/** * sends json response back to the client. */json(data: object|string): Promise<boolean>;/** * Redirect client to the given url */redirect(path: string,status: number=302): Promise<boolean>;/** * sends a file download attachment to the client */download(filePath: string,filename?: string): Promise<boolean>;RServer allows the ability to define custom http error files that are mapped to http error codes such as 404, etc. This is achieved by defining a httpErrors entry in your config file. See Configuring RServer for details.
RServer will automatically detect and handle any byte-range 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 on range requests.
We 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.