Skip to content

Commit

Permalink
withServer to use http.createServer instead of express, #175
Browse files Browse the repository at this point in the history
  • Loading branch information
zepumph committed Jul 12, 2021
1 parent 15be91a commit 9b33f5e
Showing 1 changed file with 47 additions and 7 deletions.
54 changes: 47 additions & 7 deletions js/common/withServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
*/


const express = require( 'express' );
const http = require( 'http' );
const fs = require( 'fs' );
const winston = require( 'winston' );

/**
Expand All @@ -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;

Expand All @@ -45,5 +82,8 @@ module.exports = function( asyncCallback, path = '..' ) {
resolve( result );
} );
} );

// 0 means it will find an open port
server.listen( 0 );
} );
};

0 comments on commit 9b33f5e

Please sign in to comment.