Skip to content

Commit

Permalink
[WIP] add base64 support
Browse files Browse the repository at this point in the history
  • Loading branch information
caub committed Jul 11, 2017
1 parent 432cd8a commit 1fb8470
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,5 +56,5 @@
"url-search-params": "^0.9.0",
"whatwg-url": "^4.0.0"
},
"dependencies": { }
"dependencies": {}
}
15 changes: 15 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,21 @@ export default function fetch(url, opts) {
const request = new Request(url, opts);
const options = getNodeRequestOptions(request);

if (/^data:/.test(url)) { // url.startsWith('data:')
const i = url.indexOf(','),
prefix = url.slice(5,i),
data = url.slice(i+1),
[type, enc] = prefix.split(';');
if (enc == 'base64') {
const buf = Buffer.from(data, 'base64');
// todo make a blob with this buffer and type
return Promise.resolve({
status: 200,
buffer: () => Promise.resolve(buf)
})
}
}

const send = (options.protocol === 'https:' ? https : http).request;

// http.request only support string as host header, this hack make custom host header possible
Expand Down
18 changes: 18 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1956,4 +1956,22 @@ describe('external encoding', () => {
});
});
});



it('should accept data urls', function() {

const dataUrl = 'data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=';

fetch(dataUrl).then(x => {
//console.log(r.status)

return x.buffer().then(b => {
console.assert(b instanceof Buffer);
})
// todo blob()
});

});

});

0 comments on commit 1fb8470

Please sign in to comment.