Skip to content

Commit

Permalink
feat: Data URI support (#659)
Browse files Browse the repository at this point in the history
Adds support for Data URIs using native methods in Node 5.10.0+
  • Loading branch information
Richienb committed Sep 7, 2019
1 parent 086be6f commit eb3a572
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/index.js
Expand Up @@ -38,6 +38,17 @@ export default function fetch(url, opts) {
throw new Error('native promise missing, set fetch.Promise to your favorite alternative');
}

if (/^data:/.test(url)) {
const request = new Request(url, opts);
try {
const data = Buffer.from(url.split(',')[1], 'base64')
const res = new Response(data.body, { headers: { 'Content-Type': data.mimeType || url.match(/^data:(.+);base64,.*$/)[1] } });
return fetch.Promise.resolve(res);
} catch (err) {
return fetch.Promise.reject(new FetchError(`[${request.method}] ${request.url} invalid URL, ${err.message}`, 'system', err));
}
}

Body.Promise = fetch.Promise;

// wrap http.request into fetch
Expand Down
25 changes: 25 additions & 0 deletions test/test.js
Expand Up @@ -2834,4 +2834,29 @@ describe('external encoding', () => {
});
});
});

describe('data uri', function() {
const dataUrl = 'data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=';

const invalidDataUrl = 'data:@@@@';

it('should accept data uri', function() {
return fetch(dataUrl).then(r => {
console.assert(r.status == 200);
console.assert(r.headers.get('Content-Type') == 'image/gif');

return r.buffer().then(b => {
console.assert(b instanceof Buffer);
});
});
});

it('should reject invalid data uri', function() {
return fetch(invalidDataUrl)
.catch(e => {
console.assert(e);
console.assert(e.message.includes('invalid URL'));
});
});
});
});

0 comments on commit eb3a572

Please sign in to comment.