73 lines
1.7 KiB
JavaScript
Executable File
73 lines
1.7 KiB
JavaScript
Executable File
#!/usr/bin/env node
|
|
// vim: set ts=2 sw=2 et tw=80:
|
|
/*
|
|
* Basic node.js HTTP server
|
|
*
|
|
*/
|
|
|
|
const http = require('http');
|
|
const url = require('url');
|
|
const fs = require('fs');
|
|
|
|
const routes = Object.create(null);
|
|
|
|
// Configure your routing table here...
|
|
//routes['URL'] = function;
|
|
|
|
routes['files'] = (req, res) => {
|
|
const FILE_TYPES = {
|
|
html: 'text/html',
|
|
css: 'text/css',
|
|
txt: 'text/plain',
|
|
mp4: 'video/mp4',
|
|
ogg: 'video/ogg',
|
|
gif: 'image/gif',
|
|
jpg: 'image/jpeg',
|
|
jpeg: 'image/jpeg',
|
|
png: 'image/png',
|
|
mpeg: 'audio/mpeg',
|
|
js: 'application/javascript',
|
|
json: 'application/json',
|
|
pdf: 'application/pdf',
|
|
zip: 'application/zip'
|
|
};
|
|
|
|
const uri = url.parse(req.url).pathname.substring('/files'.length);
|
|
const file = __dirname + '/NodeStaticFiles' + uri;
|
|
const name = file.substring(file.lastIndexOf('/') + 1);
|
|
const ext = name.substring(name.indexOf('.') + 1);
|
|
|
|
console.log(file, name, ext);
|
|
|
|
fs.readFile(file, (err, data) => {
|
|
if (err) {
|
|
res.writeHead(404, { 'Content-Type': 'text/html' });
|
|
res.end('File not found: ' + JSON.stringify(err));
|
|
return;
|
|
}
|
|
|
|
res.setHeader('Content-Disposition', 'attachment; filename="' + name + '"');
|
|
res.writeHead(200, { 'Content-Type': ext in FILE_TYPES ? FILE_TYPES[ext] :
|
|
'application/octet-stream' });
|
|
res.end(data);
|
|
});
|
|
}
|
|
|
|
|
|
// Main server handler
|
|
function onRequest(req, res) {
|
|
const pathname = url.parse(req.url).pathname;
|
|
const uri = pathname.split('/', 3)[1];
|
|
|
|
if (typeof routes[uri] === 'function') {
|
|
routes[uri](req, res);
|
|
} else {
|
|
res.writeHead(404);
|
|
res.end();
|
|
}
|
|
}
|
|
|
|
|
|
http.createServer(onRequest).listen(3000);
|
|
console.log('Server started at localhost:3000');
|