UNPKG

@axway/api-builder-uri-utils

Version:

A collection of URI utility functions for API Builder

57 lines (52 loc) 1.6 kB
const fs = require('fs'); function getDataImageURIType(file) { const match = file.match(/\.(?:bmp|jpeg|jpg|png|gif|tiff|tif|svg)$/); if (!match) { throw new Error(`file must be bmp, jpg, jpeg, png, gif, tiff, or svg: ${file}`); } let type = match[0].substr(1); if (type === 'svg') { type = 'svg+xml'; } else if (type === 'jpg') { type = 'jpeg'; } else if (type === 'tif') { type = 'tiff'; } return type; } /** * Converts an image file to a data-uri. The file type must be identifiable * from its extension, and must be one of: bmp, jpeg, jpg, png, gif, tif, * tiff, svg. * @param {string} file - The image file to convert to a data-uri. * @returns {string} The file encoded as a data-uri. * @async */ function iconFileToDataImageURI(file) { const type = getDataImageURIType(file); return new Promise((resolve, reject) => { fs.readFile(file, (err, data) => { if (err) { return reject(err); } const bdata = data.toString('base64'); return resolve(`data:image/${type};base64,${bdata}`); }); }); } /** * Converts an image file to a data-uri. The file type must be identifiable * from its extension, and must be one of: bmp, jpeg, jpg, png, gif, tif, * tiff, svg. * @param {string} file - The image file to convert to a data-uri. * @returns {string} The file encoded as a data-uri. */ function iconFileToDataImageURISync(file) { const type = getDataImageURIType(file); const bdata = fs.readFileSync(file).toString('base64'); return `data:image/${type};base64,${bdata}`; } module.exports = { iconFileToDataImageURI, iconFileToDataImageURISync };