Skip to content

Commit

Permalink
Replace express with builtin node server
Browse files Browse the repository at this point in the history
Alternative to long-standing webpack-contrib#212

Express in this project does not add much value. Middleware api is not
necessary for 1.5 middlwares. We can try to use node server directly.

Serving static is left for express middleware. Can be replaced with
something smaller in another PR.
  • Loading branch information
TrySound committed Nov 30, 2020
1 parent 313fac1 commit 22a92f8
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 36 deletions.
67 changes: 48 additions & 19 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -37,11 +37,11 @@
"acorn-walk": "^8.0.0",
"chalk": "^4.1.0",
"commander": "^6.2.0",
"express": "^4.17.1",
"filesize": "^6.1.0",
"gzip-size": "^6.0.0",
"lodash": "^4.17.20",
"opener": "^1.5.2",
"serve-static": "^1.14.1",
"ws": "^7.3.1"
},
"devDependencies": {
Expand Down
43 changes: 27 additions & 16 deletions src/viewer.js
Expand Up @@ -4,7 +4,7 @@ const http = require('http');

const WebSocket = require('ws');
const _ = require('lodash');
const express = require('express');
const ejs = require('ejs');
const {bold} = require('chalk');

const Logger = require('./Logger');
Expand All @@ -13,6 +13,7 @@ const {open} = require('./utils');
const {renderViewer} = require('./template');

const projectRoot = path.resolve(__dirname, '..');
const viewsRoot = path.join(projectRoot, 'views');

function resolveTitle(reportTitle) {
if (typeof reportTitle === 'function') {
Expand Down Expand Up @@ -48,23 +49,33 @@ async function startServer(bundleStats, opts) {

if (!chartData) return;

const app = express();
app.use(express.static(`${projectRoot}/public`));

app.get('/', (req, res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
const html = renderViewer({
mode: 'server',
title: resolveTitle(reportTitle),
chartData,
defaultSizes,
enableWebSocket: true
});
return res.end(html);
const serveStaticMiddleware = serveStatic(`${projectRoot}/public`);

const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/') {
const html = renderViewer({
mode: 'server',
title: resolveTitle(reportTitle),
chartData,
defaultSizes,
enableWebSocket: true
});
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(html);
} else {
serveStaticMiddleware(req, res, err => {
if (err) {
console.error(err.stack || err.toString());
res.writeHead(500);
res.end();
} else {
res.writeHead(404);
res.end();
}
});
}
});

const server = http.createServer(app);

await new Promise(resolve => {
server.listen(port, host, () => {
resolve();
Expand Down

0 comments on commit 22a92f8

Please sign in to comment.