Skip to content

Instantly share code, notes, and snippets.

@benmerckx
Created April 7, 2017 10:06
Show Gist options
  • Save benmerckx/d47cb44023cefdb3c28a5d23935e34ff to your computer and use it in GitHub Desktop.
Save benmerckx/d47cb44023cefdb3c28a5d23935e34ff to your computer and use it in GitHub Desktop.
const fs = require('fs')
const path = require('path')
const matcher = /xlink:href="data:(img|image)\/([a-z]+);base64,([^"]+)"/gi
const file = process.argv.pop()
const noop = function() {}
fs.readFile(file, 'utf-8', function (err, data) {
if (err) return console.error(err)
const name = path.basename(file, '.svg')
let newData = data
let matches, i = 0
while (matches = matcher.exec(data)) {
const format = matches[2], encoded = matches[3]
const img = name + '_' + (i++) + '.' + format
const contents = Buffer.from(encoded, 'base64')
fs.writeFile(img, contents, noop)
newData = newData.replace(matches[0], 'xlink:href="'+img+'"')
}
fs.writeFile(name + '_extracted.svg', newData, noop)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment