UNPKG

@argdown/node

Version:

Async Argdown application for node.js

58 lines 2.33 kB
import { imageSize } from "image-size"; import { ArgdownPluginError } from "@argdown/core"; import axios from "axios"; import { constants, promises as fs } from "fs"; import path from "path"; export class ImageSizePlugin { name = "ImageSizePlugin"; runAsync = async (request, _response, _logger) => { if (!request.images || !request.images.files) { return; } for (const image of Object.values(request.images.files)) { if (!image.path) { return; } try { let dimensions; if (image.width && image.height) { continue; } if (image.path.startsWith("https:") || image.path.startsWith("http:")) { dimensions = await this.getSizeFromRemoteFile(image.path); } else { try { const baseDir = request.inputPath && !!path.extname(request.inputPath) ? path.dirname(request.inputPath) : request.inputPath || ""; await fs.access(path.resolve(baseDir, image.path), constants.F_OK | constants.R_OK); const fileBuffer = await fs.readFile(path.resolve(baseDir, image.path)); dimensions = imageSize(fileBuffer); } catch (err) { dimensions = await this.getSizeFromRemoteFile(image.path); } } if (!dimensions) { continue; } image.width = dimensions.width; image.height = dimensions.height; } catch (err) { if (err instanceof Error) { throw new ArgdownPluginError(this.name, "image-size-failed", `'Getting the image size of '${image.path}' failed. ${err.message}`); } } } }; getSizeFromRemoteFile = async (path) => { const response = await axios.get(path, { responseType: "arraybuffer" }); const buffer = Buffer.from(response.data, "binary"); return imageSize(buffer); }; } //# sourceMappingURL=ImageSizePlugin.js.map