server.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #!/usr/bin/env node
  2. // Dependencies
  3. const http = require('http');
  4. const url = require('url');
  5. const fs = require('fs');
  6. const path = require('path');
  7. const childProcess = require('child_process')
  8. // Base Directory - Assuming minimal-http-server
  9. // will be accessed from its own folder.
  10. const baseDir = path.join(__dirname, '.');
  11. // Create a server
  12. const httpServer = http.createServer((request, response) => {
  13. const parsedUrl = url.parse(request.url, true);
  14. let pathName = parsedUrl.pathname;
  15. if (pathName == "/") {
  16. pathName = "/index.html"
  17. }
  18. // Get the contentType based on the file extension
  19. const responseContentType = getContentType(pathName);
  20. // Set the 'Content-Type' in response header
  21. response.setHeader('Content-Type', responseContentType);
  22. fs.readFile(`${baseDir}${pathName}`, (error, data) => {
  23. if (!error) {
  24. response.writeHead(200);
  25. response.end(data);
  26. } else {
  27. console.log(error);
  28. response.writeHead(404);
  29. response.end('404 - File Not Found');
  30. }
  31. });
  32. });
  33. // Mime Types
  34. const mimeTypes = {
  35. '.html': 'text/html',
  36. '.jpg': 'image/jpeg',
  37. '.css': 'text/css',
  38. '.js': 'text/javascript',
  39. '.png': 'image/png',
  40. '.ico': 'image/x-icon',
  41. };
  42. // Get the content type for a given path
  43. const getContentType = pathName => {
  44. // Set the default content type
  45. let contentType = 'application/octet-stream';
  46. // Set the contentType based on mime type
  47. for (var key in mimeTypes) {
  48. if (mimeTypes.hasOwnProperty(key)) {
  49. if (pathName.indexOf(key) > -1) {
  50. contentType = mimeTypes[key];
  51. }
  52. }
  53. }
  54. return contentType;
  55. };
  56. let port = 3000
  57. let host = '127.0.0.1'
  58. httpServer.listen(port, () => {
  59. console.log(`\x1b[32m%s\x1b[0m`, `Server is running at http://${host}:${port}`);
  60. var url = `http://${host}:${port}`;
  61. var start = (process.platform == 'darwin' ? 'open' : process.platform == 'win32' ? 'start' : 'xdg-open');
  62. var child = childProcess.exec(`${start} ${url}`);
  63. // child.on('exit', function() {
  64. // httpServer.close()
  65. // })
  66. });