netscape-bookmark-export-converter
Version:
Converts Netscape Bookmark Format files used by popular web browsers to an array of objects containing individual bookmarks URI's and their respective folder tags.
87 lines (86 loc) • 2.91 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.useCheerioToConvertStringToJson = exports.reduceToArray = exports.noNull = exports.sanitize = void 0;
/* eslint-disable no-console */
/* eslint-disable no-param-reassign */
/* eslint-disable import/extensions */
/* eslint-disable import/no-unresolved */
const cheerio_1 = require("cheerio");
/**
* Uses JSON stringify to santize undefinded and null branches
*
* @param obj
* @returns
*/
const sanitize = (obj) => JSON.parse(JSON.stringify(obj, (key, value) => (value === null ? undefined : value)));
exports.sanitize = sanitize;
/**
* Removes all null values from the nested object
*
* @param currentValue
* @returns
*/
const noNull = (currentValue) => {
if (currentValue && typeof currentValue === 'object' && Array.isArray(currentValue.children)) {
currentValue.children = currentValue.children.filter(exports.noNull);
}
return currentValue !== null;
};
exports.noNull = noNull;
/**
* Reduces nested JSON object to array
*
* @private
* @param obj
* @returns
*/
const reduceToArray = (jsonDataArray) => jsonDataArray.reduce((previousValue, currentValue) => {
if (currentValue === null || currentValue === void 0 ? void 0 : currentValue.url) {
return previousValue.concat([currentValue]);
}
if (currentValue === null || currentValue === void 0 ? void 0 : currentValue.children) {
return previousValue.concat((0, exports.reduceToArray)(currentValue.children));
}
return previousValue.concat([]);
}, []);
exports.reduceToArray = reduceToArray;
/**
* Uses Cheerio to convert bookmark file data to a stringified JSON Object
*
* @function
* @private
* @param fileData
* @returns
*/
const useCheerioToConvertStringToJson = (fileData) => {
try {
const $ = (0, cheerio_1.load)(fileData);
const jsonDataTree = ({ tagName, children = [] }, tags) => {
if (tagName === 'dt' && children[0].tagName === 'a') {
return {
url: children[0].attribs.href || '',
tags,
};
}
if (tagName === 'dt' && children[0].tagName === 'h3') {
const tagText = tags.length
? tags.concat([children[0].children[0].data.trim()])
: [children[0].children[0].data.trim()];
return {
children: children.map((child) => jsonDataTree(child, tagText)),
};
}
if (children.length > 1) {
return {
children: children.map((child) => jsonDataTree(child, tags)),
};
}
return {};
};
return jsonDataTree($('body')[0], []);
}
catch (_error) {
return {};
}
};
exports.useCheerioToConvertStringToJson = useCheerioToConvertStringToJson;