Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const path = require('path');
- const http = require('http');
- const fs = require('fs');
- const arg = process.argv.at(2);
- const cwd = process.cwd();
- const webDir = arg ? path.isAbsolute(arg) ? arg : path.join(cwd, arg) : cwd;
- const port = process.env.port || 8080;
- const mimeTypeMap = {
- 'bin': 'application/octet-stream',
- 'css': 'text/css',
- 'gif': 'image/gif',
- 'htm': 'text/html',
- 'html': 'text/html',
- 'jpeg': 'image/jpeg',
- 'jpg': 'image/jpeg',
- 'js': 'application/javascript',
- 'json': 'application/json',
- 'png': 'image/png',
- 'txt': 'text/plain',
- };
- const lookUpMimeType = (fileName) => {
- const extension = fileName.replace(/^.*\.(\w+)$/, '$1').toLowerCase();
- return mimeTypeMap[extension] ?? mimeTypeMap.bin;
- };
- const handleFileFetch = (req, res) => {
- const { url } = req;
- const urlPath = url.replace(/[?#].*/, '');
- const pathName = path.join(webDir, urlPath.replace(/\/$/, '/index.html'));
- if (!fs.existsSync(pathName)) {
- res.writeHead(404);
- res.end();
- return;
- }
- const stat = fs.lstatSync(pathName);
- if (stat.isDirectory()) {
- res.writeHead(303, { location: urlPath + '/' });
- res.end();
- return;
- }
- res.writeHead(200, {
- 'content-type': lookUpMimeType(pathName),
- 'content-length': stat.size,
- });
- const stream = fs.createReadStream(pathName);
- stream.on('data', (chunk) => res.write(chunk));
- stream.on('end', () => res.end());
- stream.on('error', error => {
- console.error(error);
- res.writeHead(500);
- res.end();
- });
- };
- const server = http.createServer((req, res) => {
- try {
- handleFileFetch(req, res);
- } catch(error) {
- console.error(error);
- res.writeHead(500);
- res.end();
- }
- });
- server.listen(port, () => {
- console.log('hosting', webDir);
- console.log(`http://localhost:${port} started`);
- });
Add Comment
Please, Sign In to add comment