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

express-service

v1.7.0

Published

Express server running inside ServiceWorker

Downloads

117

Readme

express-service

ExpressJS server running inside ServiceWorker

NPM

Build status semantic-release

Read Run Express server in your browser blog post.

As a proof of concept I have been able to intercept fetch requests from the page and serve them using an ExpressJS running inside a ServiceWorker.

See live demo (use Chrome or Opera) where a complete TodoMVC Express app is running a ServiceWorker. Demo source.

The ExpressJS server

The ExpressJS server can be found in src/demo-server.js, it has 2 pages

var express = require('express')
var app = express()
function sendIndexPage (req, res) {
  res.send(indexPage) // simple HTML5 text
}
function sendAboutPage (req, res) {
  res.send(aboutPage) // simple HTML text
}
app.get('/', sendIndexPage)
app.get('/about', sendAboutPage)
module.exports = app

You can try running the server in stand alone server using src/stand-alone.js It is very simple and uses the Express as a callback to Node http server

var app = require('./demo-server')
var http = require('http')
var server = http.createServer(app)
server.listen(3000)

Use

See [src/]

const expressService = require('express-service')
const app = require('./express-server')
expressService(app)

You can also cache specific static resources by providing their urls to add offline ability to your web application

const cacheName = 'my-server-v1'
const cacheUrls = ['/', 'app.css', 'static/foo/script.js']
expressService(app, cacheUrls, cacheName)

"Real world" example can be found in bahmutov/todomvc-express-and-service-worker

The ExpressJS wrapper inside ServiceWorker

We intercept each request and then create mock Node ClientRequet and Node Response, fake enough to fool the Express. When the Express is done rendering chunk, we return a Promise object back to the page.

var url = require('url') // standard Node module
self.addEventListener('fetch', function (event) {
  const parsedUrl = url.parse(event.request.url)
  console.log(myName, 'fetching page', parsedUrl.path)
  if (/* requesting things Express should not know about */) {
    return fetch(event.request)
  }
  event.respondWith(new Promise(function (resolve) {
    var req = { /* fake request */ }
    var res = { /* fake response */ }
    function endWithFinish (chunk, encoding) {
      const responseOptions = {
        status: res.statusCode || 200,
        headers: {
          'Content-Length': res.get('Content-Length'),
          'Content-Type': res.get('Content-Type')
        }
      }
      // return rendered page back to the browser
      resolve(new Response(chunk, responseOptions))
    }
    res.end = endWithFinish
    app(req, res)
  }))
})

This experiment is still pretty raw, but it has 3 main advantages right now

  • The server can be tested and used just like normal stand alone Express server
  • The pages arrive back to the browser from ServiceWorker fully rendered, creating better experience.
  • Except for the initial page that can be very simple (just register and activate the ServiceWorker), the rest of the pages does not need to run the application JavaScript code!

Related

  • serviceworkers-ware - Express-like middleware stacks for processing inside a ServiceWorker, but not the real ExpressJS
  • bottle-service - ServiceWorker interceptor that you can use to cache updated HTML to make sure the page arrives "pre-rendered" on next load for instant start up.

Building and testing example

npm run build
npm run dev-start
open localhost:3007

Small print

Author: Gleb Bahmutov © 2015

License: MIT - do anything with the code, but don't blame me if it does not work.

Spread the word: tweet, star on github, etc.

Support: if you find any problems with this module, email / tweet / open issue on Github

MIT License

Copyright (c) 2015 Gleb Bahmutov

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.