1
|
|
|
var raml2html = require('raml2html'); |
2
|
|
|
var chalk = require('chalk'); |
3
|
|
|
var emoji = require('node-emoji'); |
4
|
|
|
var fs = require('fs'); |
5
|
|
|
var path = require('path'); |
6
|
|
|
var http = require('http'); |
7
|
|
|
var url = require('url'); |
8
|
|
|
|
9
|
|
|
var enviroment = process.env.npm_package_config_enviroment; |
10
|
|
|
|
11
|
|
|
var apiDir = path.join(__dirname, '../../api/'); |
12
|
|
|
var ramlFile = path.join(__dirname, '../../api/api.raml'); |
13
|
|
|
|
14
|
|
|
process.stdout.write(chalk.gray(emoji.emojify('[ ] Server Documentazione API (' + enviroment + ") from "+ ramlFile +"\n"))); |
15
|
|
|
|
16
|
|
|
var server = http.createServer(function (req, res) { |
17
|
|
|
// console.log(`${req.method} ${req.url}`); |
18
|
|
|
process.stdout.write(chalk.gray(emoji.emojify('[ ] Request ' + `${req.method} ${req.url}` +"\n"))); |
19
|
|
|
|
20
|
|
|
// parse URL |
21
|
|
|
var parsedUrl = url.parse(req.url); |
22
|
|
|
// extract URL path |
23
|
|
|
let pathname = `${parsedUrl.pathname}`; |
24
|
|
|
// based on the URL path, extract the file extention. e.g. .js, .doc, ... |
25
|
|
|
var ext = path.parse(pathname).ext; |
26
|
|
|
// maps file extention to MIME types |
27
|
|
|
var mimeType = { |
28
|
|
|
'.html': 'text/html', |
29
|
|
|
'.json': 'application/json' |
30
|
|
|
}; |
31
|
|
|
pathnameFull = path.normalize(apiDir + pathname); |
|
|
|
|
32
|
|
|
// console.log(pathnameFull); |
33
|
|
|
|
34
|
|
|
if ( pathname == '/end' ) { |
35
|
|
|
// console.log('/end'); |
36
|
|
|
res.statusCode = '204'; |
37
|
|
|
res.end(); |
38
|
|
|
process.exit(0); |
|
|
|
|
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
fs.exists(pathnameFull, function (exist) { |
42
|
|
|
if(!exist) { |
43
|
|
|
// if the file is not found, return 404 |
44
|
|
|
res.statusCode = 404; |
45
|
|
|
res.end(`File ${pathname} not found!`); |
46
|
|
|
return; |
47
|
|
|
} |
48
|
|
|
// if is a directory, then look for index.html |
49
|
|
|
if (fs.statSync(pathnameFull).isDirectory()) { |
50
|
|
|
pathnameFull += '/index.html'; |
|
|
|
|
51
|
|
|
} |
52
|
|
|
// read file from file system |
53
|
|
|
fs.readFile(pathnameFull, function(err, data){ |
54
|
|
|
if(err){ |
55
|
|
|
res.statusCode = 500; |
56
|
|
|
res.end(`Error getting the file: ${err}.`); |
57
|
|
|
} else { |
58
|
|
|
// if the file is found, set Content-type and send data |
59
|
|
|
res.setHeader('Content-type', mimeType[ext] || 'text/plain' ); |
60
|
|
|
res.end(data); |
61
|
|
|
} |
62
|
|
|
}); |
63
|
|
|
}); |
64
|
|
|
}); |
65
|
|
|
|
66
|
|
|
server.listen(9999, '127.0.0.1'); |
67
|
|
|
|
68
|
|
|
process.stdout.write(chalk.gray(emoji.emojify('[ ] Server listening ' + apiDir + ' on port ' + 9999 +"\n"))); |
69
|
|
|
|