Skip to content

Commit cedad46

Browse files
author
xiaomingplus
committed
for update
1 parent 5427e17 commit cedad46

File tree

7 files changed

+642
-0
lines changed

7 files changed

+642
-0
lines changed

bin/start-server

Lines changed: 206 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,206 @@
1+
#!/usr/bin/env node
2+
3+
'use strict';
4+
5+
var colors = require('colors/safe'),
6+
os = require('os'),
7+
httpServer = require('../lib/http-server'),
8+
mockLib = require('../lib/mock'),
9+
portfinder = require('portfinder'),
10+
opener = require('opener'),
11+
argv = require('optimist')
12+
.boolean('cors')
13+
.argv;
14+
15+
var ifaces = os.networkInterfaces();
16+
17+
if (argv.h || argv.help) {
18+
console.log([
19+
'usage: http-server [path] [options]',
20+
'',
21+
'options:',
22+
' -p Port to use [8899]',
23+
' -a Address to use [0.0.0.0]',
24+
' -d Show directory listings [true]',
25+
' -i Display autoIndex [true]',
26+
' -g --gzip Serve gzip files when possible [false]',
27+
' -e --ext Default file extension if none supplied [none]',
28+
' -s --silent Suppress log messages from output',
29+
' --cors[=headers] Enable CORS via the "Access-Control-Allow-Origin" header',
30+
' Optionally provide CORS headers list separated by commas',
31+
' -o [path] Open browser window after starting the server',
32+
' -c Cache time (max-age) in seconds [3600], e.g. -c10 for 10 seconds.',
33+
' To disable caching, use -c-1.',
34+
' -U --utc Use UTC time format in log messages.',
35+
'',
36+
' -P --proxy Fallback proxy if the request cannot be resolved. e.g.: http://someurl.com',
37+
'',
38+
' -S --ssl Enable https.',
39+
' -C --cert Path to ssl cert file (default: cert.pem).',
40+
' -K --key Path to ssl key file (default: key.pem).',
41+
'',
42+
' -r --robots Respond to /robots.txt [User-agent: *\\nDisallow: /]',
43+
' -h --help Print this list and exit.'
44+
].join('\n'));
45+
process.exit();
46+
}
47+
48+
//先处理mock的情况
49+
50+
var mock = argv._[0] === 'mock';
51+
if (mock) {
52+
var proxy = argv.proxy;
53+
let path = argv.path;
54+
var opts = {};
55+
if (proxy) {
56+
opts.proxy = proxy;
57+
}
58+
if (path) {
59+
opts.path = path;
60+
}
61+
return mockLib(argv._[1], opts).then((data) => {
62+
process.exit();
63+
}).catch(e => {
64+
process.exit();
65+
})
66+
//
67+
}
68+
69+
var port = argv.p || parseInt(process.env.PORT, 10),
70+
host = argv.a || '0.0.0.0',
71+
ssl = !!argv.S || !!argv.ssl,
72+
proxy = argv.P || argv.proxy,
73+
utc = argv.U || argv.utc,
74+
logger;
75+
76+
if (!argv.s && !argv.silent) {
77+
logger = {
78+
info: console.log,
79+
request: function (req, res, error) {
80+
var date = utc ? new Date().toUTCString() : new Date();
81+
if (error) {
82+
logger.info(
83+
'[%s] "%s %s" Error (%s): "%s"',
84+
date, colors.red(req.method), colors.red(req.url),
85+
colors.red(error.status.toString()), colors.red(error.message)
86+
);
87+
} else {
88+
logger.info(
89+
'[%s] "%s %s" "%s"',
90+
date, colors.cyan(req.method), colors.cyan(req.url),
91+
req.headers['user-agent']
92+
);
93+
}
94+
}
95+
};
96+
} else if (colors) {
97+
logger = {
98+
info: function () {},
99+
request: function () {}
100+
};
101+
}
102+
103+
if (!port) {
104+
portfinder.basePort = 8899;
105+
portfinder.getPort(function (err, port) {
106+
if (err) {
107+
throw err;
108+
}
109+
listen(port);
110+
});
111+
} else {
112+
listen(port);
113+
}
114+
115+
function listen(port) {
116+
var options = {
117+
root: argv._[0],
118+
cache: argv.c,
119+
showDir: argv.d,
120+
autoIndex: argv.i,
121+
gzip: argv.g || argv.gzip,
122+
robots: argv.r || argv.robots,
123+
ext: argv.e || argv.ext,
124+
logFn: logger.request,
125+
proxy: proxy
126+
};
127+
128+
if (argv.cors) {
129+
options.cors = true;
130+
if (typeof argv.cors === 'string') {
131+
options.corsHeaders = argv.cors;
132+
}
133+
}
134+
135+
if (ssl) {
136+
options.https = {
137+
cert: argv.C || argv.cert || 'cert.pem',
138+
key: argv.K || argv.key || 'key.pem'
139+
};
140+
}
141+
142+
if (argv.pathQueryKeys) {
143+
if (argv.pathQueryKeys === 'false') {
144+
options.pathQueryKeys = false;
145+
} else {
146+
options.pathQueryKeys = argv.pathQueryKeys.split(',');
147+
148+
}
149+
}
150+
151+
var server = httpServer.createServer(options);
152+
server.listen(port, host, function () {
153+
var canonicalHost = host === '0.0.0.0' ? '127.0.0.1' : host,
154+
protocol = ssl ? 'https://' : 'http://';
155+
156+
logger.info([colors.yellow('Starting up http-server, serving '),
157+
colors.cyan(server.root),
158+
ssl ? (colors.yellow(' through') + colors.cyan(' https')) : '',
159+
colors.yellow('\nAvailable on:')
160+
].join(''));
161+
162+
if (argv.a && host !== '0.0.0.0') {
163+
logger.info((' ' + protocol + canonicalHost + ':' + colors.green(port.toString())));
164+
} else {
165+
Object.keys(ifaces).forEach(function (dev) {
166+
ifaces[dev].forEach(function (details) {
167+
if (details.family === 'IPv4') {
168+
logger.info((' ' + protocol + details.address + ':' + colors.green(port.toString())));
169+
}
170+
});
171+
});
172+
}
173+
174+
if (typeof proxy === 'string') {
175+
logger.info('Unhandled requests will be served from: ' + proxy);
176+
}
177+
178+
logger.info('Hit CTRL-C to stop the server');
179+
if (argv.o) {
180+
opener(
181+
protocol + '//' + canonicalHost + ':' + port, {
182+
command: argv.o !== true ? argv.o : null
183+
}
184+
);
185+
}
186+
});
187+
}
188+
189+
if (process.platform === 'win32') {
190+
require('readline').createInterface({
191+
input: process.stdin,
192+
output: process.stdout
193+
}).on('SIGINT', function () {
194+
process.emit('SIGINT');
195+
});
196+
}
197+
198+
process.on('SIGINT', function () {
199+
logger.info(colors.red('http-server stopped.'));
200+
process.exit();
201+
});
202+
203+
process.on('SIGTERM', function () {
204+
logger.info(colors.red('http-server stopped.'));
205+
process.exit();
206+
});

lib/mock.js

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
var axios = require('axios');
2+
var url = require('url');
3+
var fs = require('fs');
4+
var path = require('path');
5+
var mkdirp = require('mkdirp');
6+
7+
function createFile(_path, content) {
8+
if (/\.json/.test(_path)) {} else {
9+
_path = _path + '.json';
10+
}
11+
return new Promise((resolve, reject) => {
12+
mkdirp(path.dirname(_path), function (err) {
13+
if (err) {
14+
return reject(err);
15+
}
16+
fs.writeFile(_path, content, function (err) {
17+
if (err) {
18+
return reject(err);
19+
} else {
20+
console.log('file create success,path:', (_path))
21+
return resolve()
22+
}
23+
})
24+
})
25+
26+
})
27+
}
28+
29+
module.exports = function (_url, options) {
30+
options = Object.assign({}, options);
31+
let urlObj = url.parse(_url,true);
32+
let opts = {
33+
url: _url,
34+
}
35+
if (options.proxy) {
36+
let proxyObj = url.parse(options.proxy);
37+
opts.proxy = {};
38+
opts.proxy.host = proxyObj.hostname;
39+
opts.proxy.port = proxyObj.port || 80;
40+
}
41+
let userPath = options.path || './mocks';
42+
let pathQueryKeys = [];
43+
if (options.pathQueryKeys) {
44+
pathQueryKeys = options.pathQueryKeys
45+
} else {
46+
47+
if (options.pathQueryKeys === false) {
48+
49+
} else {
50+
pathQueryKeys = ['d', 'c', 'm']; //默认CI框架的风格
51+
}
52+
}
53+
let paths = [urlObj.pathname];
54+
pathQueryKeys.forEach((item) => {
55+
if(urlObj.query[item]){
56+
paths.push(urlObj.query[item])
57+
}
58+
})
59+
let pathFinal = path.join.apply(null, paths);
60+
return axios(opts).then((data) => {
61+
62+
return createFile(path.join(userPath,pathFinal), JSON.stringify(data.data, null, 2)).then(() => {}).catch(e => {
63+
console.error('e', e);
64+
})
65+
}).catch(e => {
66+
return createFile(path.join(userPath, pathFinal), JSON.stringify({})).catch(e => {
67+
console.error('e', e);
68+
})
69+
})
70+
}

mocks/config.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
module.exports = {
2+
//路由配置
3+
'routes': {
4+
//方法,all代表全部方法
5+
'all': {
6+
//路径:响应的内容
7+
'/api/path1/path2': {
8+
'data':{
9+
list:[
10+
'1','2'
11+
]
12+
}
13+
},
14+
//如果是CI框架类型的话这里需要把dcm直接按照路径写,访问的时候使用/node?d=dd&c=cc&m=mm或者/node/dd/cc/mm都可以访问
15+
'/node/dd/cc/mm':{
16+
'data':{
17+
list:[
18+
'3','4'
19+
]
20+
}
21+
}
22+
}
23+
}
24+
25+
}

mocks/index.html

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<html>
2+
<head>
3+
<title>node.js http server</title>
4+
</head>
5+
<body>
6+
7+
<h1>Serving up static files like they were turtles strapped to rockets.</h1>
8+
9+
<img src="./img/turtle.png"/>
10+
</body>
11+
</html>
12+

mocks/node/path1/file1/method1.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"methods":"here"
3+
}

0 commit comments

Comments
 (0)