-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathangular-http-server.js
More file actions
executable file
·176 lines (156 loc) · 4.96 KB
/
Copy pathangular-http-server.js
File metadata and controls
executable file
·176 lines (156 loc) · 4.96 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
#!/usr/bin/env node
import fs from "fs";
import path from "path";
import mime from "mime";
import pem from "pem";
import https from "https";
import http from "http";
import open from "open";
import minimist from "minimist";
import { fileURLToPath } from "url";
import getFilePathFromUrl from "./get-file-path-from-url.js";
import proxyHandler from "./proxy.js";
// Get current file directory equivalent to __dirname in CJS
const __filename = fileURLToPath(import.meta.url);
const argv = minimist(process.argv.slice(2));
// if using config file, load that first
if (argv.config) {
let configPath;
if (path.isAbsolute(argv.config)) {
configPath = argv.config;
} else {
configPath = path.join(process.cwd(), argv.config);
}
const configModule = await import(configPath);
const getConfig = configModule.default || configModule;
let config;
if (typeof getConfig === "function") {
config = getConfig(argv);
} else {
config = getConfig;
}
// supplement argv with config, but CLI args take precedence
argv = Object.assign(config, argv);
}
// Pre-process arguments
const useHttps = argv.ssl || argv.https;
const basePath = argv.path ? path.resolve(argv.path) : process.cwd();
const baseHref = argv.baseHref || "";
const rootFile = argv.rootFile || "index.html";
const port = getPort(argv.p);
const NO_PATH_FILE_ERROR_MESSAGE = `Error: rootFile ${rootFile} could not be found in the specified path `;
// As a part of the startup - check to make sure we can access rootFile
returnDistFile(true);
// Start with/without https
let server;
if (useHttps) {
const startSSLCallback = (err, keys) => {
if (err) {
throw err;
}
const options = {
key: keys.serviceKey,
cert: keys.certificate,
rejectUnauthorized: false,
};
server = https.createServer(options, requestListener);
start();
};
if (argv.key && argv.cert) {
const serviceKey = fs.readFileSync(argv.key);
const certificate = fs.readFileSync(argv.cert);
startSSLCallback(null, { serviceKey, certificate });
} else {
pem.createCertificate({ days: 1, selfSigned: true }, startSSLCallback);
}
} else {
server = http.createServer(requestListener);
start();
}
function start() {
server.listen(port, function () {
if (argv.open || argv.o) {
// open a browser tab
const host = argv.host || "localhost";
open((useHttps ? "https" : "http") + "://" + host + ":" + port);
}
return console.log("Listening on " + port);
});
}
// HELPERS
function requestListener(req, res) {
// When we hit the proxy, return
if (argv.proxy && proxyHandler(req, res, argv.proxy)) {
return;
}
// Add CORS header if option chosen
if (argv.cors) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Request-Method", "*");
res.setHeader("Access-Control-Allow-Methods", "OPTIONS, GET");
res.setHeader(
"Access-Control-Allow-Headers",
"authorization, content-type"
);
// When the request is for CORS OPTIONS (rather than a page) return just the headers
if (req.method === "OPTIONS") {
res.writeHead(200);
res.end();
return;
}
}
const safeFullFileName = getFilePathFromUrl(req.url, basePath, {
baseHref,
});
fs.stat(safeFullFileName, function (err, stats) {
let fileBuffer;
if (!err && stats.isFile()) {
fileBuffer = fs.readFileSync(safeFullFileName);
let ct = mime.getType(safeFullFileName);
log(`Sending ${safeFullFileName} with Content-Type ${ct}`);
res.writeHead(200, { "Content-Type": ct });
} else {
log(
`Route %s, replacing with rootFile ${rootFile}`,
safeFullFileName
);
fileBuffer = returnDistFile();
res.writeHead(200, { "Content-Type": "text/html" });
}
res.write(fileBuffer);
res.end();
});
}
function getPort(portNo) {
if (portNo) {
const portNum = parseInt(portNo);
if (!isNaN(portNum)) {
return portNum;
} else {
throw new Error("Provided port is not a number!");
}
} else {
return 8080;
}
}
function returnDistFile(displayFileMessages = false) {
let distPath;
try {
if (displayFileMessages) {
log("Serving from path: %s", basePath);
}
distPath = path.join(basePath, rootFile);
if (displayFileMessages) {
log("Using default file: %s", distPath);
}
return fs.readFileSync(distPath);
} catch (e) {
console.warn(NO_PATH_FILE_ERROR_MESSAGE + "%s", basePath);
process.exit(1);
}
}
function log() {
if (!argv.silent) {
console.log.apply(console, arguments);
}
}