This repository was archived by the owner on Apr 16, 2020. It is now read-only.
forked from pmb0/express-sharp
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.js
84 lines (77 loc) · 1.99 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const path = require('path')
const http = require('http')
const fs = require('fs')
const express = require('express')
const expressSharp = require('./')
const imageDir = path.resolve(__dirname, 'test', 'images')
const files = fs.readdirSync(imageDir)
function paramsFrom(dict) {
const params = new URLSearchParams()
Object.entries(dict).forEach(([name, value]) => params.set(name, value))
return params
}
function serve(middleware) {
return new Promise((resolve, reject) => {
try {
const app = express()
app.use(middleware)
const server = http.createServer(app)
server.on('error', reject)
server.listen(0, '0.0.0.0', () => {
const { address, port } = server.address()
resolve(`http://${address}:${port}`)
})
} catch (e) {
reject(e)
}
})
}
async function main() {
const baseHost = await serve(express.static(imageDir))
const demo = express.Router()
demo.use('/express-sharp', expressSharp({
baseHost
}))
files.forEach(filename => {
demo.get(`/${filename}`, (req, res) => {
const original = new URL(filename, baseHost).href
const params = paramsFrom(req.query)
const resized = `/express-sharp/${filename}?${params.toString()}`
res.status(200).send(`
<html>
<head>
<title>Demo @express-sharp</title>
<style>
body {
font-size: 16px;
margin: 0;
padding: 0;
background-color: #${req.query.bg || 'ffeebb'};
}
figure {
border: 1px solid black;
padding: 2rem;
margin: 1rem;
}
</style>
</head>
<body>
<figure>
<img src="${original}">
<figcaption>Original ${filename}</figcaption>
</figure>
<figure>
<img src="${resized}">
<figcaption>Resized: ${resized}</figcaption>
</figure>
</body>
</html>
`.trim())
})
})
const demoURLBase = await serve(demo)
files.forEach(filename => {
console.log(new URL(`/${filename}`, demoURLBase).href)
})
}
main()