-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
92 lines (78 loc) · 1.89 KB
/
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
81
82
83
84
85
86
87
88
89
90
91
92
var http = require( 'http' );
var fs = require( 'fs' );
var path = require( 'path' );
var server = http.createServer();
var settings = require('./config.json');
console.log( settings );
var docroot = settings.docroot || 'docs';
var MIME =
{
'css': 'text/css',
'gif': 'image/gif',
'gz': 'application/gzip',
'html': 'text/html',
'ico': 'image/x-icon',
'jpg': 'image/jpeg',
'js': 'text/javascript',
'png': 'image/png',
'txt': 'text/plain',
'zip': 'application/zip',
'wasm': 'application/wasm',
};
if ( settings.mime )
{
Object.keys( settings.mime ).forEach( function( key )
{
MIME[ key ] = settings.mime[ key ];
} );
}
function e404( res )
{
res.writeHead( 404, { 'Content-Type': 'text/plain' } );
res.write( '404: page not found.' );
res.end();
}
function fileExists( filepath )
{
try
{
fs.statSync(filepath);
return true
} catch( err ) {}
return false;
}
function responseText( res, filepath, mime )
{
fs.readFile( filepath, 'utf-8', function( err, data )
{
if( err ) { return e404( res ); }
res.writeHead( 200, { 'Content-Type': mime } );
res.write( data );
res.end();
} );
}
function responseBinary( res, filepath, mime )
{
fs.readFile( filepath, function( err, data )
{
if( err ) { return e404( res ); }
res.writeHead( 200, { 'Content-Type': mime } );
res.write( data );
res.end();
} );
}
server.on( 'request', function ( req, res )
{
var filepath = ( req.url || '/' ).split( '?' )[ 0 ];
if ( filepath.match( /\/$/ ) ) { filepath += 'index.html'; }
filepath = path.join( docroot, filepath );
if ( !fileExists( filepath ) ) { return e404( res ); }
var extname = path.extname( filepath ).replace( '.', '' );
var mime = MIME[ extname ] || 'text/plain';
if ( mime.match( /^text/ ) ) {
responseText( res, filepath, mime );
} else {
responseBinary( res, filepath, mime );
}
} );
server.listen( settings.port || 8080, settings.host || '127.0.0.1' );