Created
December 19, 2018 21:50
-
-
Save ntpz/6f811e7182f429c8c227dfcbe03baa5c to your computer and use it in GitHub Desktop.
Convert chrome bookmarks file to json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'), | |
path = require('path'), | |
{ promisify } = require('util'), | |
readFileAsync = promisify(fs.readFile), | |
writeFileAsync = promisify(fs.writeFile), | |
inPath = path.join(__dirname, 'bookmarks.html'), | |
outPath = path.join(__dirname, 'bookmarks.json'), | |
linkRx = /<A([^>]+)>([^<]+)<\/A>/ig; | |
const extractAttr = (attrName, attrStr) => { | |
let pos; | |
if ((pos = attrStr.indexOf(attrName)) === -1) { | |
return null; | |
} | |
pos = pos + attrName.length + 2; | |
return attrStr.substring(pos, attrStr.indexOf('"', pos)); | |
} | |
const parseLink = (attrs, title) => { | |
let hash, attrValue; | |
const rv = {}; | |
title = title.replace('"', '"'); | |
if ((hash = title.indexOf('#')) === -1) { | |
rv.title = title; | |
} | |
else { | |
rv.title = title.substr(0, hash).trim(); | |
rv.tags = title.substr(hash + 1).split(' ').map(s => s.trim()).filter(s => s.length); | |
} | |
if ((attrValue = extractAttr('HREF', attrs)) !== null) { | |
rv.url = attrValue; | |
} | |
else { // No URL - bailing out | |
return null; | |
} | |
if ((attrValue = extractAttr('ADD_DATE', attrs)) !== null) { | |
rv.add_date = attrValue; | |
} | |
if ((attrValue = extractAttr('ICON_URI', attrs)) !== null) { | |
rv.icon_uri = attrValue; | |
} | |
return rv; | |
} | |
const convert = html => { | |
const rv = []; | |
let link; | |
while ((link = linkRx.exec(html)) !== null) { | |
link = parseLink(link[1], link[2]); | |
if (link !== null) { | |
rv.push(link); | |
} | |
} | |
return JSON.stringify(rv); | |
} | |
readFileAsync(inPath) | |
.then(convert) | |
.then(json => writeFileAsync(outPath, json)) | |
.then(result => console.log(`Done!`)) | |
.catch(console.error); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment