UNPKG

dk-srv

Version:
55 lines (54 loc) 1.75 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const fs = require("fs"); const path = require("path"); const url = require("url"); exports.srv_static = (item) => { const parsedUrl = url.parse(item.reqHttp.url); // extract URL path const baseDir = process.cwd() + "/"; let pathname = baseDir + "public/" + parsedUrl.pathname; let ok = 1; const ext = path.parse(pathname).ext; const map = { '.ico': 'image/x-icon', '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.css': 'text/css', '.png': 'image/png', '.jpg': 'image/jpeg', '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.svg': 'image/svg+xml', '.pdf': 'application/pdf', '.doc': 'application/msword', }; if (map[ext]) { ok = 0; } fs.exists(pathname, (exist) => { if (!exist) { item.resHttp.statusCode = 404; item.resHttp.end(`File ${pathname} not found!`); return; } // if is a directory search for index file matching the extention if (fs.statSync(pathname).isDirectory()) { pathname += '/index' + ext; } // read file from file system fs.readFile(pathname, (err, data) => { if (err) { item.resHttp.statusCode = 500; item.resHttp.end(`Error getting the file: ${err}.`); } else { // if the file is found, set Content-type and send data item.resHttp.setHeader('Content-type', map[ext] || 'text/plain'); item.resHttp.end(data); } }); }); return ok; };