actionhero
Version:
The reusable, scalable, and quick node.js API server for stateless and stateful applications
179 lines (178 loc) • 7.56 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.StaticFileInitializer = void 0;
const fs = require("fs");
const path = require("path");
const Mime = require("mime");
const index_1 = require("../index");
/**
* Contains helpers for returning flies to connections.
*/
class StaticFileInitializer extends index_1.Initializer {
constructor() {
super();
/**
* For a connection with `connection.params.file` set, return a file if we can find it, or a not-found message.
* `searchLocations` will be checked in the following order: first paths in this project, then plugins.
* This can be used in Actions to return files to clients. If done, set `data.toRender = false` within the action.
* return is of the form: {connection, error, fileStream, mime, length}
*/
this.get = async (connection, counter = 0) => {
let file;
if (!connection.params.file || !index_1.api.staticFile.searchPath(counter)) {
return index_1.api.staticFile.sendFileNotFound(connection, await index_1.config.errors.fileNotProvided(connection));
}
if (!path.isAbsolute(connection.params.file)) {
file = path.normalize(path.join(index_1.api.staticFile.searchPath(counter), connection.params.file));
}
else {
file = connection.params.file;
}
if (file.indexOf(path.normalize(index_1.api.staticFile.searchPath(counter))) !== 0) {
return index_1.api.staticFile.get(connection, counter + 1);
}
else {
const { exists, truePath } = await index_1.api.staticFile.checkExistence(file);
if (exists) {
return index_1.api.staticFile.sendFile(truePath, connection);
}
else {
return index_1.api.staticFile.get(connection, counter + 1);
}
}
};
this.searchPath = (counter = 0) => {
if (index_1.api.staticFile.searchLocations.length === 0 ||
counter >= index_1.api.staticFile.searchLocations.length) {
return null;
}
else {
return index_1.api.staticFile.searchLocations[counter];
}
};
this.sendFile = async (file, connection) => {
let lastModified;
try {
const stats = await asyncStats(file);
const mime = Mime.getType(file);
const length = stats.size;
const start = new Date().getTime();
lastModified = stats.mtime;
const fileStream = fs.createReadStream(file);
index_1.api.staticFile.fileLogger(fileStream, connection, start, file, length);
await new Promise((resolve) => {
fileStream.on("open", () => {
resolve(null);
});
});
return { connection, fileStream, mime, length, lastModified };
}
catch (error) {
return index_1.api.staticFile.sendFileNotFound(connection, await index_1.config.errors.fileReadError(connection, error));
}
};
this.fileLogger = (fileStream, connection, start, file, length) => {
fileStream.on("end", () => {
const duration = new Date().getTime() - start;
index_1.api.staticFile.logRequest(file, connection, length, duration, true);
});
fileStream.on("error", (error) => {
throw error;
});
};
this.sendFileNotFound = async (connection, errorMessage) => {
connection.error = new Error(errorMessage);
index_1.api.staticFile.logRequest("{not found}", connection, null, null, false);
const response = await index_1.config.errors.fileNotFound(connection);
return {
connection,
error: response,
mime: "text/html",
length: response.length,
};
};
this.checkExistence = async (file) => {
try {
const stats = await asyncStats(file);
if (stats.isDirectory()) {
const indexPath = file + "/" + index_1.config.general.directoryFileType;
return index_1.api.staticFile.checkExistence(indexPath);
}
if (stats.isSymbolicLink()) {
let truePath = await asyncReadLink(file);
truePath = path.normalize(truePath);
return index_1.api.staticFile.checkExistence(truePath);
}
if (stats.isFile()) {
return { exists: true, truePath: file };
}
return { exists: false, truePath: file };
}
catch (error) {
return { exists: false, truePath: file };
}
};
this.logRequest = (file, connection, length, duration, success) => {
(0, index_1.log)(`[ file @ ${connection.type} ]`, index_1.config.general.fileRequestLogLevel, {
to: connection.remoteIP,
file: file,
requestedFile: connection.params.file,
size: length,
duration: duration,
success: success,
});
};
this.name = "staticFile";
this.loadPriority = 510;
}
async initialize() {
index_1.api.staticFile = {
searchLocations: [],
get: this.get,
searchPath: this.searchPath,
sendFile: this.sendFile,
fileLogger: this.fileLogger,
sendFileNotFound: this.sendFileNotFound,
checkExistence: this.checkExistence,
logRequest: this.logRequest,
};
// load in the explicit public paths first
if (index_1.config.general.paths) {
index_1.config.general.paths.public.forEach(function (p) {
index_1.api.staticFile.searchLocations.push(path.normalize(p));
});
}
// source the public directories from plugins
for (const plugin of Object.values(index_1.config.plugins)) {
if (plugin.public !== false) {
const pluginPublicPath = path.normalize(path.join(plugin.path, "public"));
if (fs.existsSync(pluginPublicPath) &&
index_1.api.staticFile.searchLocations.indexOf(pluginPublicPath) < 0) {
index_1.api.staticFile.searchLocations.push(pluginPublicPath);
}
}
}
(0, index_1.log)("static files will be served from these directories", "debug", index_1.api.staticFile.searchLocations);
}
}
exports.StaticFileInitializer = StaticFileInitializer;
async function asyncStats(file) {
return new Promise((resolve, reject) => {
fs.stat(file, (error, stats) => {
if (error) {
return reject(error);
}
return resolve(stats);
});
});
}
async function asyncReadLink(file) {
return new Promise((resolve, reject) => {
fs.readlink(file, (error, linkString) => {
if (error) {
return reject(error);
}
return resolve(linkString);
});
});
}