giovani-rubim

Node HTTP server

Dec 27th, 2019 (edited)
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const path = require('path');
  2. const http = require('http');
  3. const fs = require('fs');
  4. const arg = process.argv.at(2);
  5. const cwd = process.cwd();
  6. const webDir = arg ? path.isAbsolute(arg) ? arg : path.join(cwd, arg) : cwd;
  7. const port = process.env.port || 8080;
  8. const mimeTypeMap = {
  9.     'bin': 'application/octet-stream',
  10.     'css': 'text/css',
  11.     'gif': 'image/gif',
  12.     'htm': 'text/html',
  13.     'html': 'text/html',
  14.     'jpeg': 'image/jpeg',
  15.     'jpg': 'image/jpeg',
  16.     'js': 'application/javascript',
  17.     'json': 'application/json',
  18.     'png': 'image/png',
  19.     'txt': 'text/plain',
  20. };
  21. const lookUpMimeType = (fileName) => {
  22.     const extension = fileName.replace(/^.*\.(\w+)$/, '$1').toLowerCase();
  23.     return mimeTypeMap[extension] ?? mimeTypeMap.bin;
  24. };
  25. const handleFileFetch = (req, res) => {
  26.     const { url } = req;
  27.     const urlPath = url.replace(/[?#].*/, '');
  28.     const pathName = path.join(webDir, urlPath.replace(/\/$/, '/index.html'));
  29.     if (!fs.existsSync(pathName)) {
  30.         res.writeHead(404);
  31.         res.end();
  32.         return;
  33.     }
  34.     const stat = fs.lstatSync(pathName);
  35.     if (stat.isDirectory()) {
  36.         res.writeHead(303, { location: urlPath + '/' });
  37.         res.end();
  38.         return;
  39.     }
  40.     res.writeHead(200, {
  41.         'content-type': lookUpMimeType(pathName),
  42.         'content-length': stat.size,
  43.     });
  44.     const stream = fs.createReadStream(pathName);
  45.     stream.on('data', (chunk) => res.write(chunk));
  46.     stream.on('end', () => res.end());
  47.     stream.on('error', error => {
  48.         console.error(error);
  49.         res.writeHead(500);
  50.         res.end();
  51.     });
  52. };
  53. const server = http.createServer((req, res) => {
  54.     try {
  55.         handleFileFetch(req, res);
  56.     } catch(error) {
  57.         console.error(error);
  58.         res.writeHead(500);
  59.         res.end();
  60.     }
  61. });
  62. server.listen(port, () => {
  63.     console.log('hosting', webDir);
  64.     console.log(`http://localhost:${port} started`);
  65. });
  66.  
Add Comment
Please, Sign In to add comment