1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | 'use strict';
|
8 |
|
9 | const http = require('http');
|
10 | const url = require('url');
|
11 | const path = require('path');
|
12 | const os = require('os');
|
13 | const pako = require('pako');
|
14 | const chalk = require('chalk');
|
15 | const execFile = require('child_process').execFile;
|
16 | const mimeTypes = require('./mime');
|
17 | const config = require('./serconf');
|
18 | const T = require('./tools');
|
19 | const LiveServer = require('./live/liveReloadServer').LiveServer;
|
20 | const liveApp = require('./live/liveApp');
|
21 | const getGupackConfig = require('./live/liveReloadConfig');
|
22 |
|
23 |
|
24 | const userCustomConfig = getGupackConfig();
|
25 | const hostname = userCustomConfig['host'];
|
26 | const port = userCustomConfig['port'];
|
27 | const sport = userCustomConfig['sport'];
|
28 | const liveReloadDelay = userCustomConfig['liveDelay'];
|
29 |
|
30 |
|
31 | const basePath = userCustomConfig.buildDir && T.Path.isAbsolute(userCustomConfig.buildDir) ? userCustomConfig.buildDir : T.Path.resolve(process.cwd(), 'dist');
|
32 | let isOpenBrowser, oldRealPath;
|
33 |
|
34 |
|
35 | if (!basePath) {
|
36 | throw new Error(T.msg.red('\u672a\u8bbe\u7f6e\u6b63\u786e\u7684\u9879\u76ee\u8def\u5f84'));
|
37 | }
|
38 |
|
39 |
|
40 | function createLiveServer(gupack) {
|
41 | isOpenBrowser = gupack.openBrowser;
|
42 |
|
43 | const server = liveApp(doFile);
|
44 |
|
45 | server.listen(port, hostname, listen);
|
46 | return server;
|
47 | }
|
48 |
|
49 | function doFile(req, res) {
|
50 | let headers = {
|
51 | 'Accept-Ranges': 'bytes',
|
52 | 'Content-Type': 'text/plain',
|
53 | 'Access-Control-Allow-Origin': '*',
|
54 | 'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE',
|
55 | 'Access-Control-Allow-Headers': 'Content-Type',
|
56 | 'Access-Control-Allow-Credentials': 'true',
|
57 | 'Timing-Allow-Origin': '*',
|
58 | Server: 'Gupack, NodeJS/' + process.version
|
59 | };
|
60 |
|
61 | let pathname = url.parse(req.url).pathname.replace(/\.\./g, '');
|
62 | if (pathname.slice(-1) === '/') {
|
63 | pathname += config.indexFile.file;
|
64 | }
|
65 | let realPath = path.join(basePath, path.normalize(pathname));
|
66 | if (pathname === '/favicon.ico') {
|
67 | realPath = path.resolve(__dirname, '../', path.normalize(pathname));
|
68 | }
|
69 | if (/mock(Data)?.*?\.json$/gi.test(pathname)) {
|
70 | realPath = path.resolve(basePath, '../', pathname.replace(/^\//, ''));
|
71 | }
|
72 |
|
73 |
|
74 | if (!T.fs.existsSync(realPath)) {
|
75 | sendResponse(req, res, 404, 'This request URL " + pathname + " was not found on this server.', headers);
|
76 | return;
|
77 | }
|
78 |
|
79 | let stats = T.fs.statSync(realPath);
|
80 | if (!stats) {
|
81 | sendResponse(req, res, 404, 'This request URL " + pathname + " was not found on this server.', headers);
|
82 | return;
|
83 | }
|
84 |
|
85 |
|
86 |
|
87 | if (stats.isDirectory()) {
|
88 | realPath = path.join(realPath, '/', config.indexFile.file);
|
89 | }
|
90 |
|
91 | T.fs.readFile(realPath, 'binary', (err, file) => {
|
92 | if (err) {
|
93 |
|
94 | T.log.red('--->>> \u8bfb\u53d6\u6587\u4ef6\u5931\u8d25 ');
|
95 | sendResponse(req, res, 500, err.toLocaleString(), headers);
|
96 | } else {
|
97 | let extname = path.extname(realPath).replace(/^\./i, '');
|
98 | headers['Content-Type'] = (mimeTypes[extname] || 'text/plain') + '; charset=UTF-8';
|
99 |
|
100 |
|
101 | let cacher = setHeaderCache(req, stats, extname, headers);
|
102 | if (304 === cacher) {
|
103 | sendResponse(req, res, 304, 'Not Modified', headers);
|
104 | return;
|
105 | } else {
|
106 | headers = cacher;
|
107 | }
|
108 |
|
109 |
|
110 | if (config.liveReload.match.test(extname)) {
|
111 | file = implanteStyleCode(file);
|
112 | file = implanteScriptCode(file);
|
113 | oldRealPath && liveServer.unwatch(oldRealPath);
|
114 | liveServer.watching(realPath);
|
115 | oldRealPath = realPath;
|
116 | T.log.yellow('.................page reload................');
|
117 | }
|
118 |
|
119 |
|
120 | if (extname.match(config.Gzip.match)) {
|
121 | let gziper = setHeaderGzip(req, file, headers);
|
122 | file = gziper.content;
|
123 | headers = gziper.headers;
|
124 | }
|
125 |
|
126 |
|
127 | headers['Content-Length'] = file.length;
|
128 |
|
129 | sendResponse(req, res, 200, file, headers);
|
130 | }
|
131 | });
|
132 | }
|
133 |
|
134 | function listen() {
|
135 | let url = `http://${hostname}:${port}/${getIndexFile()}`;
|
136 | T.log.yellow(chalk.underline.bgBlue(`Server running at ${url}`));
|
137 | connectSocket();
|
138 | isOpenBrowser && openBrowse(url);
|
139 | }
|
140 |
|
141 | function getIndexFile() {
|
142 | return userCustomConfig.indexFile;
|
143 | }
|
144 |
|
145 | function openBrowse(url) {
|
146 | let osType = os.type();
|
147 | let shellFile = /windows/gi.test(osType) ? 'open.cmd' : /macos/gi.test(osType) ? 'open' : 'xdg-open';
|
148 | shellFile = T.Path.resolve(__dirname, '../shell', shellFile);
|
149 | execFile(shellFile, [url]);
|
150 | }
|
151 |
|
152 |
|
153 |
|
154 |
|
155 |
|
156 |
|
157 |
|
158 |
|
159 |
|
160 |
|
161 | function sendResponse(req, res, status, body, headers, charType) {
|
162 | res.writeHead(status, headers);
|
163 | res.write(body, charType || 'binary');
|
164 | res.end();
|
165 | }
|
166 |
|
167 |
|
168 |
|
169 |
|
170 |
|
171 |
|
172 | function implanteScriptCode(content) {
|
173 | let scriptCode = T.getFileContent(T.Path.resolve(__dirname, 'live/liveReloadBrowser.js'));
|
174 | let tag = '<script id="' + Math.random() * 999999 + '" data-host="' + hostname + '" data-socket="true" data-port="' + sport + '">';
|
175 |
|
176 | scriptCode = T.replaceVar(scriptCode, null, sport);
|
177 | tag += scriptCode + '</script></body>';
|
178 | content = content.replace('</body>', tag);
|
179 | return content;
|
180 | }
|
181 |
|
182 | function implanteStyleCode(content) {
|
183 | let styleCode = T.getFileContent(T.Path.resolve(__dirname, 'live/liveReloadStyle.css'));
|
184 | let tag = '<style id="' + Math.random() * 999999 + '" data-host="' + hostname + '" data-socket="true" data-port="' + sport + '">';
|
185 |
|
186 | tag += styleCode + '</style></head>';
|
187 | content = content.replace('</head>', tag);
|
188 | return content;
|
189 | }
|
190 |
|
191 |
|
192 |
|
193 |
|
194 |
|
195 |
|
196 |
|
197 |
|
198 | function setHeaderGzip(req, content, headers) {
|
199 |
|
200 | let bin = new Buffer(content, 'binary');
|
201 | let acceptEncoding = req.headers['accept-encoding'] || '';
|
202 | if (/\bgzip\b/gi.test(acceptEncoding)) {
|
203 | headers['Content-Encoding'] = 'gzip';
|
204 | content = pako.gzip(new Uint8Array(bin), { to: 'string' });
|
205 | } else if (/\bdeflate\b/gi.test(acceptEncoding)) {
|
206 | headers['Content-Encoding'] = 'deflate';
|
207 | content = pako.gzip(new Uint8Array(bin), { to: 'string' });
|
208 | }
|
209 | return { content: content, headers: headers };
|
210 | }
|
211 |
|
212 |
|
213 |
|
214 |
|
215 |
|
216 |
|
217 |
|
218 |
|
219 |
|
220 | function setHeaderCache(req, stats, extname, headers) {
|
221 | let lastModified = stats.mtime.toUTCString();
|
222 | let ifModifiedSince = 'If-Modified-Since'.toLowerCase();
|
223 | headers['Last-Modified'] = lastModified;
|
224 | if (extname.match(config.Expires.fileMatch)) {
|
225 | let expires = new Date();
|
226 | expires.setTime(expires.getTime() + config.Expires.maxAge * 1000);
|
227 | headers['Expires'] = expires.toUTCString();
|
228 | headers['Cache-Control'] = 'max-age=' + config.Expires.maxAge;
|
229 | }
|
230 |
|
231 | if (req.headers[ifModifiedSince] && lastModified === req.headers[ifModifiedSince]) {
|
232 | return 304;
|
233 | }
|
234 | return headers;
|
235 | }
|
236 |
|
237 |
|
238 |
|
239 |
|
240 | let liveServer;
|
241 |
|
242 | function connectSocket() {
|
243 | if (liveServer) return false;
|
244 | liveServer = new LiveServer({ port: sport, liveDelay: liveReloadDelay });
|
245 | }
|
246 |
|
247 | function emitBuilding() {
|
248 | liveServer && liveServer.send('<<<-----start building----->>>');
|
249 | }
|
250 |
|
251 | module.exports = {
|
252 | createLiveServer,
|
253 | emitBuilding
|
254 | };
|