Skip to content

Commit

Permalink
add error event
Browse files Browse the repository at this point in the history
  • Loading branch information
52cik committed Dec 29, 2016
1 parent 2521945 commit 39163a1
Showing 1 changed file with 51 additions and 8 deletions.
59 changes: 51 additions & 8 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ const zlib = require('zlib');
const url = require('url');
const fs = require('fs');

const PORT = process.env.PORT || process.argv[3] || 3000;
const baseDir = process.env.DIR || path.resolve(process.argv[2] || '.');
const PORT = process.env.PORT || process.argv[3] || 3000;

const maxAge = 60 * 60 * 24 * 365; // 1 year
const gzipTypes = /(?:html|css|js|xml)/ig;
Expand All @@ -28,15 +28,17 @@ const mimeTypes = {
};

const app = http.createServer((req, res) => {
if (req.method !== 'GET' && req.method !== 'HEAD') {
// method not allowed
res.writeHead(405, 'Method Not Allowed', {'Allow': 'GET, HEAD', 'Content-Length': '0'});
if (req.method !== 'GET' && req.method !== 'HEAD') { // method not allowed
res.writeHead(405, 'Method Not Allowed', {'Allow': 'GET, HEAD', 'Content-Length': 0});
return res.end();
}

sendFile(req, res, url.parse(req.url).pathname);
});

/**
* Send file
*/
function sendFile(req, res, pathname) {
let filename = path.join(baseDir, unescape(pathname));

Expand All @@ -55,7 +57,7 @@ function sendFile(req, res, pathname) {
return sendFile(req, res, path.join(pathname, 'index.html'));
}

var lastModified = stat.mtime.toUTCString();
let lastModified = stat.mtime.toUTCString();
res.setHeader('Last-Modified', lastModified);

let expires = new Date();
Expand Down Expand Up @@ -87,10 +89,51 @@ function sendFile(req, res, pathname) {
});
}

app.on('error', onError);
app.on('listening', onListening);

module.exports.app = app;

module.exports.listen = _ => {
app.listen(PORT, _ => {
console.log(`Server running at http://localhost:${PORT}/`);
});
app.listen(PORT, '0.0.0.0');
};


/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}

let bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;

// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(`${bind} requires elevated privileges`);
process.exit(1);
break;
case 'EADDRINUSE':
console.error(`${bind} is already in use`);
process.exit(1);
break;
default:
throw error;
}
}

/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
let addr = app.address();
let bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;

console.log(`Server listening on ${bind}`);
}

0 comments on commit 39163a1

Please sign in to comment.