UNPKG

serverless-plugin-static

Version:
57 lines (56 loc) 2.38 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const http = require("http"); const url = require("url"); const path = require("path"); const fs_1 = require("fs"); const fileExtToContentTypeMap = { '.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', }; const handler = (folder) => (req, res) => __awaiter(void 0, void 0, void 0, function* () { try { const parsedUrl = url.parse(String(req.url)); const pathname = path.join(folder, String(parsedUrl.pathname)); const { ext } = path.parse(pathname); const data = yield fs_1.promises.readFile(pathname); res.setHeader('Content-Type', fileExtToContentTypeMap[ext] || 'text/plain'); return res.end(data); } catch (error) { if (error.code === 'ENOENT') { res.statusCode = 404; return res.end(`File not found`); } res.statusCode = 500; return res.end(`Error getting the file: ${error}.`); } }); exports.default = (serverless, { folder, port }) => new Promise((resolve) => { const requestHandler = handler(folder); const server = http.createServer(requestHandler); server.listen(port, () => { serverless.cli.log(`[ Static ] serving static files from ${folder} folder`); serverless.cli.log(`[ Static ] serving static files on http://localhost:${port}`); resolve(server); }); });