npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@velocejs/server

v0.9.5

Published

Server core using uWebsocket.js with additional helpers

Downloads

25

Readme

@velocejs/server

The package is built on top of uWebSocket.js.

Installation

$ npm i @velocejs/server

How to

All the examples using Typscript. We will start from the lower level code.

createApp(opt?: AppOptions): TemplatedApp

shutdownServer(token: us_listen_socket)

import { createApp, shutdownServer } from '@velocejs/server'
const port = 9001
let connectedSocket

createApp()
  .get('/*', (res: HttpResponse) => {
    res.end('Hello')
  })
  .listen(port, token => {
    if (token) {
      connectedSocket
      console.log(`Server is running ${port}`)
    }
  })
// now some time later if you need to gracefully shutdown your server
shutdownServer(connectedSocket)

If you pass the following configuration object, then it will create a SSLApp

{
  key_file_name: 'path/to/key.pem',
  cert_file_name: 'path/to/cert.pem',
  passphrase: 'your_pass_phrase'
}

You can also specify a host when you call the listen method

createApp()
  // ... add route handlers
  .listen('0.0.0.0', 3456, token => {
    // the rest of your code
  })

Automatically determine port number

You can let the server to decided which port number to use (very handy when you need to run multiple instance per CPU). All you have to do is to set the startup port to 0.

import { createApp, getPort } from '@velocejs/server'
const port = 0 // <-- here

createApp()
  .any('/*', (res: HttpResponse) => {
    res.end('Hello')
  })
  .listen(port, token => {
    const thisPortNumber = getPort(token)
    // it will return the actual port number this server is running on
  })

async readJsonAsync(res: HttpResponse): Promise<any>

writeJson(res: HttpResponse, json: any): void

Extract the JSON from the request using readJsonAsync and serve up your JSON using writeJsonAsync (It creates all the appropriate headers for you)

// store the token for use later  
let listenSocket: us_listen_socket = null
// create app
createApp()
  .post('/*', async (res: HttpResponse) => {
    const json: object = await readJsonAsync(res)
    // do your thing with your json
    writeJson(res, {OK: true})
  })
  .listen(port, token => {
    listenSocket = token
    if (!token) {
      console.log(`Start up server failed on`, port)
    }
  })

async serveStatic(path: string | Array<string>): void

Serve up your static assets or your actual rendered HTML page etc.

const app = createApp()
  .get('/assets/*', serveStatic('/path/to/assets')) // can be an array of multiple folders
  .listen(port, token => {
    console.log("running")
  })

All you have to do is the provide the url, and where your files are (you can pass array of directories), and serveStatic takes care of the rest.

async bodyParser(res: HttpResponse, req: HttpRequest, onAborted?: () => void): Promise<UwsRespondBody>

bodyParser is now a standalone project @velocejs/bodyparser

This will help you to parse the request input, and put into easier to use format.

import bodyParser from '@velocejs/bodyparser'

const app = createApp()
  .get('/*', async (res: HttpResponse, req: HttpRequest) => {
    const result: UwsRespondBody = await bodyParser(
      res,
      req,
      /* optional onAbortedHandler */ () => console.log(`something wrong`)
    )
    // do your thing with the result  
  })
  .listen(port, token => {
    console.log("running")
  })

The result is a UwsRespondBody type object with this signature:

type UwsRespondBody = {
 url: string
 method: string
 query: string,
 headers: UwsStringPairObj
 params: any
 payload?: Buffer
}

Please visit @velocejs/bodyparser for more info.

(Class) UwsServer

This is an all-in-one solution to create the (UWS) server

import { UwsServer } from '@velocejs/server'

const app: UwsServer = new UwsServer()
// by default we randomly assign a port, see below for more info
app.run([
  {
    type: 'any',
    path: '/*',
    handler: (res: HttpResponse) => {
      res.onAborted(() => {
        console.log(`server aborted`)
      })
      res.end(`Hello`)
    }
  },
  { //  we also support WebSocket
    type: 'ws',
    path: '/socket/*',
    handler: {
      open: function(ws: WebSocket) {
        ws.send('Hello World')
      },
      message: function(ws: WebSocket, message: ArrayBuffer) {
        ws.send('Got your message')
      }
    }
  }
])

Please note the res.onAborted if you don't provide one, and when something wrong happen with the server, the server will simply crash. If you provide one, then even the handler throw error, the server will keep on running.


Next will be all available public methods

UwsServer.onStart(): void

By default there is no output, if you pass DEBUG=velocejs:server:uws-server-class in your startup script then you will able to see a start-up message.

Or you can overwrite it by using onStart setter:

app.onStart = () => console.info(`My own message`)

Please note, you have to overload this before you call app.run

UwsServer.run(handlers: UwsRouteSetup[]): void

This is the main method to create the server, apply end points (routes) and bind the server to port.

The UwsRouteSetup interface has this signature:

interface UwsRouteSetup {
  type: string
  path: string
  handler: any
}

available type options are any, get, post, put, options ,del, patch, head, connect, trace.

UwsServer.shutdown(): void

To gracefully shutdown the server

app.shutdown()

getPortNum(): number AND set portNum(port: number)

By default the server will randomly assign an unused port, you could overwrite it by:

  1. portNum setter
  2. using the node environment variable PORT (this will have higher priority)

Assume that you have put everything in a file call server.js

$ PORT=3456 node ./server.js

Or if you just stick with the randomly port, you can use this method to retrieve the port number.

const port = app.getPortNum()

hostName setter and getter

You can also specify a host name, default is localhost. There are two ways to overwrite this:

  1. hostName setter
  2. using the node environment variable HOST (this will have higher priority)

Assume that you have put everything in a file call server-with-hostname.js

$ HOST=0.0.0.0 node ./server-with-hostname.js

This is handy to write start-up script for your DevOps.


(Class) FastApi

This project is now standalone module on @velocejs/fastapi


Joel Chu (c) 2022