8000 feat: Data URI support (#659) · node-fetch/node-fetch@eb3a572 · GitHub
[go: up one dir, main page]

Skip to content

Commit eb3a572

Browse files
authored
feat: Data URI support (#659)
Adds support for Data URIs using native methods in Node 5.10.0+
1 parent 086be6f commit eb3a572

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

src/index.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,17 @@ export default function fetch(url, opts) {
3838
throw new Error('native promise missing, set fetch.Promise to your favorite alternative');
3939
}
4040

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

4354
// wrap http.request into fetch

test/test.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2834,4 +2834,29 @@ describe('external encoding', () => {
28342834
});
28352835
});
28362836
});
2837+
2838+
describe('data uri', function() {
2839+
const dataUrl = 'data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=';
2840+
2841+
const invalidDataUrl = 'data:@@@@';
2842+
2843+
it('should accept data uri', function() {
2844+
return fetch(dataUrl).then(r => {
2845+
console.assert(r.status == 200);
2846+
console.assert(r.headers.get('Content-Type') == 'image/gif');
2847+
2848+
return r.buffer().then(b => {
2849+
console.assert(b instanceof Buffer);
2850+
});
2851+
});
2852+
});
2853+
2854+
it('should reject invalid data uri', function() {
2855+
return fetch(invalidDataUrl)
2856+
.catch(e => {
2857+
console.assert(e);
2858+
console.assert(e.message.includes('invalid URL'));
2859+
});
2860+
});
2861+
});
28372862
});

0 commit comments

Comments
 (0)
0