From 9b33f5e14792135aafe84988d917da767c518ed0 Mon Sep 17 00:00:00 2001 From: zepumph Date: Mon, 12 Jul 2021 12:05:25 -0400 Subject: [PATCH] withServer to use http.createServer instead of express, https://github.com/phetsims/perennial/issues/175 --- js/common/withServer.js | 54 +++++++++++++++++++++++++++++++++++------ 1 file changed, 47 insertions(+), 7 deletions(-) diff --git a/js/common/withServer.js b/js/common/withServer.js index f83ed5e1..88738224 100644 --- a/js/common/withServer.js +++ b/js/common/withServer.js @@ -7,7 +7,8 @@ */ -const express = require( 'express' ); +const http = require( 'http' ); +const fs = require( 'fs' ); const winston = require( 'winston' ); /** @@ -20,15 +21,51 @@ const winston = require( 'winston' ); */ module.exports = function( asyncCallback, path = '..' ) { return new Promise( ( resolve, reject ) => { - const app = express(); - app.use( express.static( path ) ); - // start the server - const server = app.listen( 0, async () => { - const port = server.address().port; + // Consider using https://github.com/cloudhead/node-static or reading https://nodejs.org/en/knowledge/HTTP/servers/how-to-serve-static-files/ + const server = http.createServer( ( req, res ) => { + + // Trim query string + const tail = req.url.indexOf( '?' ) >= 0 ? req.url.substring( 0, req.url.indexOf( '?' ) ) : req.url; + const fullPath = `${process.cwd()}/${path}${tail}`; + + // See https://gist.github.com/aolde/8104861 + const mimeTypes = { + html: 'text/html', + jpeg: 'image/jpeg', + jpg: 'image/jpeg', + png: 'image/png', + js: 'text/javascript', + css: 'text/css', + gif: 'image/gif', + mp3: 'audio/mpeg', + wav: 'audio/wav', - winston.debug( 'info', `Express listening on port ${port}` ); + // needed to be added to support PhET sims. + svg: 'image/svg+xml', + json: 'application/json' + }; + const fileExtension = fullPath.split( '.' ).pop(); + const mimeType = mimeTypes[ fileExtension ]; + + if ( !mimeType ) { + throw new Error( `unsupported mime type, please add above: ${fileExtension}` ); + } + fs.readFile( fullPath, ( err, data ) => { + if ( err ) { + res.writeHead( 404 ); + res.end( JSON.stringify( err ) ); + } + else { + res.writeHead( 200, { 'Content-Type': mimeType } ); + res.end( data ); + } + } ); + } ); + server.on( 'listening', async () => { + const port = server.address().port; + winston.debug( 'info', `Server listening on port ${port}` ); let result; @@ -45,5 +82,8 @@ module.exports = function( asyncCallback, path = '..' ) { resolve( result ); } ); } ); + + // 0 means it will find an open port + server.listen( 0 ); } ); };