-
Notifications
You must be signed in to change notification settings - Fork 79
/
server.ts
54 lines (51 loc) 路 1.81 KB
/
server.ts
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
import * as http from 'http';
import * as path from 'path';
import * as util from 'util';
import * as fs from 'fs';
import * as marked from 'marked';
import serve = require('serve-handler');
import enableDestroy = require('server-destroy');
const readFile = util.promisify(fs.readFile);
export interface WebServerOptions {
// The local path that should be mounted as a static web server
root: string;
// The port on which to start the local web server
port: number;
// If markdown should be automatically compiled and served
markdown?: boolean;
// Should directories automatically serve an inde page
directoryListing?: boolean;
}
/**
* Spin up a local HTTP server to serve static requests from disk
* @private
* @returns Promise that resolves with the instance of the HTTP server
*/
export async function startWebServer(options: WebServerOptions) {
return new Promise<http.Server>((resolve, reject) => {
const server = http
.createServer(async (req, res) => {
const pathParts = req.url!.split('/').filter(x => !!x);
if (pathParts.length > 0) {
const ext = path.extname(pathParts[pathParts.length - 1]);
if (options.markdown && ext.toLowerCase() === '.md') {
const filePath = path.join(path.resolve(options.root), req.url!);
const data = await readFile(filePath, {encoding: 'utf-8'});
const result = marked(data, {gfm: true});
res.writeHead(200, {
'content-type': 'text/html',
});
res.end(result);
return;
}
}
return serve(req, res, {
public: options.root,
directoryListing: options.directoryListing,
});
})
.listen(options.port, () => resolve(server))
.on('error', reject);
enableDestroy(server);
});
}