49 lines
1.7 KiB
JavaScript
49 lines
1.7 KiB
JavaScript
"use strict";
|
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
};
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
const mime_1 = __importDefault(require("mime"));
|
|
const events_1 = require("events");
|
|
const url_1 = require("url");
|
|
const messages_1 = require("../../messages");
|
|
const create_resource_1 = __importDefault(require("./create-resource"));
|
|
const builtin_header_names_1 = __importDefault(require("../builtin-header-names"));
|
|
const DISK_RE = /^\/[A-Za-z]:/;
|
|
class FileRequest extends events_1.EventEmitter {
|
|
constructor(url) {
|
|
super();
|
|
this._url = url;
|
|
this._path = FileRequest._getPath(url);
|
|
}
|
|
async init() {
|
|
const resource = await (0, create_resource_1.default)(this._path);
|
|
if (resource.error)
|
|
this._onError(resource.error);
|
|
else
|
|
this._onOpen(resource.contentStream);
|
|
}
|
|
static _getPath(proxiedUrl) {
|
|
const parsedUrl = (0, url_1.parse)(proxiedUrl);
|
|
// @ts-ignore
|
|
let path = decodeURIComponent(parsedUrl.pathname);
|
|
if (DISK_RE.test(path))
|
|
path = path.substr(1);
|
|
return path;
|
|
}
|
|
_onError(err) {
|
|
this.emit('fatalError', (0, messages_1.getText)(messages_1.MESSAGE.cantReadFile, { url: this._url, message: err.message }));
|
|
}
|
|
_onOpen(contentStream) {
|
|
let stream = contentStream;
|
|
stream = Object.assign(stream, {
|
|
statusCode: 200,
|
|
trailers: {},
|
|
headers: { [builtin_header_names_1.default.contentType]: mime_1.default.lookup(this._path) },
|
|
});
|
|
this.emit('response', stream);
|
|
}
|
|
}
|
|
exports.default = FileRequest;module.exports = exports.default;
|
|
|