@tech_query/node-toolkit
Version:
Toolkit for Node.JS packages
50 lines (49 loc) • 1.76 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.findFile = findFile;
exports.findUp = findUp;
exports.toDataURI = toDataURI;
exports.blobFrom = blobFrom;
const fs_1 = require("fs");
const path_1 = require("path");
const mime_1 = require("mime");
const file_type_1 = require("file-type");
function findFile(name, path = '.') {
name = (0, fs_1.readdirSync)(path).find(file => file.match(name));
if (name)
return (0, path_1.join)(path, name);
}
/**
* Find files upward
*/
function* findUp(from = './') {
from = (0, path_1.resolve)(from);
while (true) {
const path = (0, path_1.join)(from, '../');
if (path === from)
break;
const file = (0, fs_1.readdirSync)((from = path));
while (file[0])
yield (0, path_1.join)(path, file.shift());
}
}
async function toDataURI(path) {
const file = await fs_1.promises.readFile(path);
const type = await (0, file_type_1.fromBuffer)(file);
return `data:${(type === null || type === void 0 ? void 0 : type.mime) || (0, mime_1.getType)(path)};base64,${file.toString('base64')}`;
}
const DataURI_pattern = /^data:(.+?\/(.+?))?(;base64)?,(\S+)/;
/**
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_Types
*/
async function blobFrom(DataURI) {
var _a;
const [MIME, extension, base64, raw] = (DataURI_pattern.exec(DataURI) || []).slice(1);
const data = Buffer.from(raw, base64 ? 'base64' : 'utf-8');
return {
MIME: MIME || ((_a = (await (0, file_type_1.fromBuffer)(data))) === null || _a === void 0 ? void 0 : _a.mime),
extension,
data
};
}