forked from MetaMask/metamask-extension
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstatic-server.js
executable file
·80 lines (67 loc) · 2.07 KB
/
static-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
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const chalk = require('chalk');
const pify = require('pify');
const createStaticServer = require('./create-static-server');
const { parsePort } = require('./lib/parse-port');
const fsStat = pify(fs.stat);
const DEFAULT_PORT = 9080;
const onResponse = (request, response) => {
if (response.statusCode >= 400) {
console.log(
chalk`{gray '-->'} {red ${response.statusCode}} ${request.url}`,
);
} else if (response.statusCode >= 200 && response.statusCode < 300) {
console.log(
chalk`{gray '-->'} {green ${response.statusCode}} ${request.url}`,
);
} else {
console.log(
chalk`{gray '-->'} {green.dim ${response.statusCode}} ${request.url}`,
);
}
};
const onRequest = (request, response) => {
console.log(chalk`{gray '<--'} {blue [${request.method}]} ${request.url}`);
response.on('finish', () => onResponse(request, response));
};
const startServer = ({ port, rootDirectory }) => {
const server = createStaticServer(rootDirectory);
server.on('request', onRequest);
server.listen(port, () => {
console.log(`Running at http://localhost:${port}`);
});
};
const parseDirectoryArgument = async (pathString) => {
const resolvedPath = path.resolve(pathString);
const directoryStats = await fsStat(resolvedPath);
if (!directoryStats.isDirectory()) {
throw new Error(`Invalid path '${pathString}'; must be a directory`);
}
return resolvedPath;
};
const main = async () => {
const args = process.argv.slice(2);
const options = {
port: process.env.port || DEFAULT_PORT,
rootDirectory: path.resolve('.'),
};
while (args.length) {
if (/^(--port|-p)$/u.test(args[0])) {
if (args[1] === undefined) {
throw new Error('Missing port argument');
}
options.port = parsePort(args[1]);
args.splice(0, 2);
} else {
options.rootDirectory = await parseDirectoryArgument(args[0]);
args.splice(0, 1);
}
}
startServer(options);
};
main().catch((error) => {
console.error(error);
process.exit(1);
});