66 lines
No EOL
1.6 KiB
JavaScript
66 lines
No EOL
1.6 KiB
JavaScript
import fs from 'fs';
|
|
import http from 'http';
|
|
import path from 'path';
|
|
|
|
const port = 8080;
|
|
|
|
const server = http.createServer((request, response) => {
|
|
const mimeType = {
|
|
'.html': 'text/html',
|
|
'.js': 'text/javascript',
|
|
'.gz': 'application/javascript',
|
|
};
|
|
const mimeEncoding = {
|
|
'.gz': 'gzip',
|
|
};
|
|
let pathname = path.join('.', request.url);
|
|
|
|
if(!fs.existsSync(pathname))
|
|
{
|
|
// If the file is not found, return 404
|
|
response.statusCode = 404;
|
|
response.end(`File ${pathname} not found!`);
|
|
return;
|
|
}
|
|
// If is a directory, then look for index.html
|
|
if (fs.statSync(pathname).isDirectory()) {
|
|
pathname = path.join(pathname, 'index.html');
|
|
}
|
|
// Read file from file system
|
|
fs.readFile(pathname, function(error, data){
|
|
if(error)
|
|
{
|
|
response.statusCode = 500;
|
|
response.end(`Error getting the file: ${error}.`);
|
|
}
|
|
else
|
|
{
|
|
// Based on the URL path, extract the file extention. e.g. .js, .doc, ...
|
|
const extension = path.parse(pathname).ext;
|
|
// Set Content-Type
|
|
response.setHeader('Content-Type', mimeType[extension] || 'text/plain' );
|
|
// If the file is found, set Content-Encoding
|
|
if(mimeEncoding[extension])
|
|
{
|
|
response.setHeader('Content-Encoding', mimeEncoding[extension]);
|
|
}
|
|
response.end(data);
|
|
}
|
|
});
|
|
});
|
|
|
|
server.listen(port, (error) => {
|
|
if (error)
|
|
return console.log(`Server cannot listen port ${port} :`, error);
|
|
console.log(`Server is listening on port ${port}`);
|
|
});
|
|
|
|
const exit = () => {
|
|
server.close();
|
|
console.log('Server stopped');
|
|
};
|
|
|
|
process.on('SIGINT', () => {
|
|
process.stdout.write('\r \r');
|
|
exit();
|
|
}); |