fetch-base64
Advanced tools
Comparing version 0.3.0 to 1.0.0
18
index.js
@@ -34,7 +34,7 @@ 'use strict'; | ||
function fetchRemote(url) { | ||
return checkMimeType(url).then( | ||
function fetchRemote(...paths) { | ||
return checkMimeType(paths).then( | ||
(mimeType) => calculatePrefix(mimeType) | ||
).then( | ||
(prefix) => remote.fetch(url).then( | ||
(prefix) => remote.fetch(...paths).then( | ||
(base64) => [base64, prefix + base64] | ||
@@ -47,11 +47,5 @@ ) | ||
return new Promise((resolve) => { | ||
const path = paths[0]; | ||
// is > 1 path directly assume local as path concatenation is not supported for remote | ||
if (paths.length > 1) { | ||
resolve(fetchLocal(...paths)); | ||
} else if (uriMatcher.isRemote(path)) { | ||
resolve(fetchRemote(path)); | ||
} else { | ||
resolve(fetchLocal(path)); | ||
} | ||
resolve( | ||
(uriMatcher.isRemote(paths[0])) ? fetchRemote(...paths) : fetchLocal(...paths) | ||
); | ||
}); | ||
@@ -58,0 +52,0 @@ } |
@@ -8,4 +8,5 @@ 'use strict'; | ||
module.exports = { | ||
fetch: (uri) => { | ||
fetch: (...paths) => { | ||
const promise = new Promise((resolve, reject) => { | ||
const uri = (paths.length > 1) ? url.resolve(...paths) : paths[0]; | ||
let options; | ||
@@ -23,3 +24,3 @@ try { | ||
if (res.statusCode !== 200) { | ||
reject(`Status code ${res.statusCode} returned when trying to fetch image`); | ||
reject(`Status code ${res.statusCode} returned when trying to fetch file`); | ||
return false; | ||
@@ -26,0 +27,0 @@ } |
{ | ||
"name": "fetch-base64", | ||
"version": "0.3.0", | ||
"version": "1.0.0", | ||
"dependencies": { | ||
@@ -5,0 +5,0 @@ "mime-db": { |
{ | ||
"name": "fetch-base64", | ||
"version": "0.3.0", | ||
"version": "1.0.0", | ||
"description": "A node package to retrieve fetch local or remote images in base64 encoding.", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
# Fetch Base64 | ||
A node package to retrieve fetch local or remote files in base64 encoding. Useful for embedding assets (images, web fonts, etc.) into HTML or CSS documents. | ||
Disclaimer: I've only used this for images so far, but there is no reason why it should not work for any other kind of file. | ||
Disclaimer: I've only used this for images so far, but there is no reason why it shouldn't work for any other kind of files. | ||
If you find a bug please report it [here](https://github.com/gamell/fetch-base64/issues). | ||
# TL;DR example | ||
# Usage | ||
@@ -45,3 +45,3 @@ ```js | ||
- `...paths` *String(s)*: Single or multiple paths which will be combined using node's [`path.resolve()`](https://nodejs.org/docs/latest/api/path.html#path_path_resolve_from_to). You can pass multiple paths to resolve a relative path to an absolute path. Some examples of valid values for this parameter: | ||
- `...paths` `<string(s)>`: Single or multiple paths which will be combined using node's [`path.resolve()`](https://nodejs.org/docs/latest/api/path.html#path_path_resolve_from_to). You can pass multiple paths to resolve a relative path to an absolute path. Some examples of valid values for this parameter: | ||
- `'/some/absolute/path/image.jpg'` | ||
@@ -53,3 +53,3 @@ - `'/base/path/to/html', './img/animation.gif'` | ||
Fetch remote files and return a promise with the file in base64 format. | ||
Fetch remote file in `url` and return a promise with the file in base64 format. | ||
@@ -60,15 +60,31 @@ User Agent is spoofed to be same as Chrome's to avoid some restrictions, but fetching could still fail for other reasons. | ||
- `url` *String*: URL where the image resides. Note that node must have access to the given URL. | ||
- `url` `<string>`: URL where the file resides. Note that node must have access to the given URL. | ||
## `fetch.auto(...paths)` | ||
## `fetch.remote(from, to)` | ||
This function will try to automatically detect the kind of path passed (`remote` or `local`) and invoke the correspondent function. | ||
Resolve url using node's [`url.resolve(from, to)`](https://nodejs.org/api/url.html#url_url_resolve_from_to), fetch remote file and return a promise with the file in base64 format. | ||
User Agent is spoofed to be same as Chrome's to avoid some restrictions, but fetching could still fail for other reasons. | ||
### Params | ||
- `...paths` *String(s)*: Accepts the same parameter as `fetch.local()`. If more than one path is passed, `local` will be assumed as path concatenation is not supported for remote URLs right now. Some examples of valid values for this parameter: | ||
- `'http://some.domain/file.png'` | ||
- `'/base/path/to/html', './img/animation.gif'` | ||
- `basePathForRelative` **String** (optional): Only used for fetching **local images**. See `fetch.local` documentation above. | ||
- `from` `<string>`: The Base URL being resolved against. | ||
- `to` `<string>`: The HREF URL being resolved. | ||
See [`url.resolve()`](https://nodejs.org/api/url.html#url_url_resolve_from_to) for more information and examples. | ||
## `fetch.auto(...mixed)` | ||
This function will do the *best effort* to automatically detect the kind of path passed (`remote` or `local`) and invoke the correspondent function. | ||
It will use the `fetch.isRemote()` function to determine if a remote url or a local path has been passed **in the first parameter**. | ||
### Params | ||
- `...mixed` `<string(s)>`: Accepts the same parameters as `fetch.local(...paths)`, `fetch.remote(url)` or `fetch.remote(from, to)` - see above. Examples of valid calls: | ||
- `fetch.auto('/base/path/to/html', './img/animation.gif');` | ||
- `fetch.auto('http://some.domain/file.png');` | ||
- `fetch.auto('http://some.domain/', 'file.png');` | ||
# Utility functions | ||
@@ -78,7 +94,7 @@ | ||
Returns `true` if the passed path (String) is local. Returns `false` otherwise. | ||
Returns `true` if the passed path (`<string>`) is local. Returns `false` otherwise. | ||
## `fetch.isRemote(path)` | ||
Returns `true` if the passed path (String) is remote. Returns `false` otherwise. | ||
Returns `true` if the passed path (`<string>`) is remote. Returns `false` otherwise. | ||
@@ -98,3 +114,3 @@ | ||
// will fetch image in /Users/bla/src/project/img/logo.jpg | ||
const doFetchLocal = fetch.local('./img/logo.jpg', '/Users/bla/src/project'); | ||
const doFetchLocal = fetch.local('/Users/bla/src/project', './img/logo.jpg'); | ||
doFetchLocal.then((data) => { | ||
@@ -104,3 +120,3 @@ console.log(`base64 image raw: ${data[0]}`); | ||
console.log(`Fetch Failed: ${reason}`) | ||
}) | ||
}); | ||
``` | ||
@@ -116,14 +132,32 @@ | ||
console.log(`Fetch Failed: ${reason}`) | ||
}) | ||
}); | ||
``` | ||
```js | ||
const doFetchRemote2 = fetch.remote('https://somedomain.com', '/image.jpg'); | ||
doFetchRemote.then((data) => { | ||
console.log(`base64 image with mimeType: ${data[1]}`); | ||
}, (reason) => { | ||
console.log(`Fetch Failed: ${reason}`) | ||
}); | ||
``` | ||
## Auto | ||
```js | ||
const doFetch = fetch.auto('https://somedomain.com/image.jpg'); | ||
const doFetchAuto = fetch.auto('https://somedomain.com/image.jpg'); | ||
doFetch.then((data) => { | ||
console.log(`base 64 image: ${data[0]}`); | ||
console.log(`base64 image: ${data[0]}`); | ||
}, (reason) => { | ||
console.log(`Fetch Failed: ${reason}`) | ||
}) | ||
}); | ||
``` | ||
```js | ||
const doFetchAuto2 = fetch.auto('/some/local/', '/path/', './image.jpg'); | ||
doFetch.then((data) => { | ||
console.log(`base64 image: ${data[0]}`); | ||
}, (reason) => { | ||
console.log(`Fetch Failed: ${reason}`) | ||
}); | ||
``` |
@@ -12,3 +12,3 @@ 'use strict'; | ||
describe('index.js', () => { | ||
describe('index.js (Unit)', () => { | ||
beforeEach(() => { | ||
@@ -58,9 +58,20 @@ sandbox = sinon.sandbox.create(); | ||
}); | ||
it('it should automatically assume local if several paths passed', (done) => { | ||
const fetchLocalStub = sandbox.stub(local, 'fetch', () => Promise.reject('incorrect path')); | ||
it('it should call fetch.remote if first path passed is remote', (done) => { | ||
const fetchRemoteStub = sandbox.stub(remote, 'fetch', () => Promise.resolve('image-data')); | ||
const shouldNotBeCalled = sandbox.spy(local, 'fetch'); | ||
index.auto('http://thisisremote.com/', '/paths/', '/image.gif').then((data) => { | ||
assert.equal(data[0], 'image-data'); | ||
sinon.assert.calledOnce(fetchRemoteStub); | ||
sinon.assert.calledWith(fetchRemoteStub, 'http://thisisremote.com/', '/paths/', '/image.gif'); | ||
assert.equal(shouldNotBeCalled.callCount, 0); | ||
done(); | ||
}).catch((e) => done(e)); | ||
}); | ||
it('it should call fetch.local if first path passed is local', (done) => { | ||
const fetchLocalStub = sandbox.stub(local, 'fetch', () => Promise.resolve('image-data')); | ||
const shouldNotBeCalled = sandbox.spy(remote, 'fetch'); | ||
index.auto('http://thisisremote.com/', '/paths/', '/image.gif').catch((reason) => { | ||
index.auto('/localPath/', '/paths/', '/image.gif').then((data) => { | ||
assert.equal(data[0], 'image-data'); | ||
sinon.assert.calledOnce(fetchLocalStub); | ||
sinon.assert.calledWith(fetchLocalStub, 'http://thisisremote.com/', '/paths/', '/image.gif'); | ||
assert.equal(reason, 'incorrect path'); | ||
sinon.assert.calledWith(fetchLocalStub, '/localPath/', '/paths/', '/image.gif'); | ||
assert.equal(shouldNotBeCalled.callCount, 0); | ||
@@ -67,0 +78,0 @@ done(); |
@@ -10,3 +10,3 @@ 'use strict'; | ||
describe('fetchLocal', () => { | ||
describe('fetchLocal (Unit)', () => { | ||
beforeEach(() => { | ||
@@ -13,0 +13,0 @@ sandbox = sinon.sandbox.create(); |
@@ -28,3 +28,3 @@ 'use strict'; | ||
describe('fetchRemote', () => { | ||
describe('fetchRemote (Unit)', () => { | ||
beforeEach(() => { | ||
@@ -66,2 +66,24 @@ sandbox = sinon.sandbox.create(); | ||
}); | ||
it('should call url.resolve if several paths passed', (done) => { | ||
setupSuccessfulResponseMock(sandbox); | ||
const urlParseStub = sandbox.stub(url, 'parse', () => ({})); | ||
const urlResolveStub = sandbox.stub(url, 'resolve', () => 'http://url.com/existing-image.gif'); | ||
fetchRemote.fetch('http://url.com', '/existing-image.gif').then(() => { | ||
assert(urlResolveStub.calledOnce); | ||
sinon.assert.calledWith(urlResolveStub, 'http://url.com', '/existing-image.gif'); | ||
assert(urlParseStub.calledWith('http://url.com/existing-image.gif')); | ||
done(); | ||
}).catch((e) => done(e)); | ||
}); | ||
it('should not call url.resolve if only one path passed', (done) => { | ||
setupSuccessfulResponseMock(sandbox); | ||
const urlParseStub = sandbox.stub(url, 'parse', () => ({})); | ||
const urlResolveStub = sandbox.stub(url, 'resolve', () => ({})); | ||
fetchRemote.fetch('http://url.com/image.gif').then(() => { | ||
assert.equal(urlResolveStub.callCount, 0); | ||
assert(urlParseStub.calledOnce); | ||
sinon.assert.calledWith(urlParseStub, 'http://url.com/image.gif'); | ||
done(); | ||
}).catch((e) => done(e)); | ||
}); | ||
describe('http.request', () => { | ||
@@ -68,0 +90,0 @@ it('should return with expected error', (done) => { |
@@ -9,3 +9,3 @@ 'use strict'; | ||
describe('Uri matcher', () => { | ||
describe('Uri matcher (Unit)', () => { | ||
beforeEach(() => { | ||
@@ -12,0 +12,0 @@ sandbox = sinon.sandbox.create(); |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
29976
17
542
0
157
13