base64-async
Advanced tools
Comparing version
{ | ||
"name": "base64-async", | ||
"version": "1.0.0", | ||
"version": "2.0.0", | ||
"description": "Non-blocking chunked base64 encoding", | ||
@@ -5,0 +5,0 @@ "main": "src/index.js", |
@@ -15,4 +15,39 @@ # base64-async | ||
## Usage | ||
```js | ||
const b64 = require('base64-async'); | ||
const fs = require('fs'); | ||
const fileBuffer = fs.readFileSync('somehugefile.jpg'); | ||
console.log(fileBuffer); | ||
// <Buffer 68 69 20 6d 75 6d ... > | ||
b64.encode(fileBuffer) | ||
.then(b64String => { | ||
console.log(b64String); | ||
// aGkgbXVt... | ||
return b64.decode(b64String); | ||
}) | ||
.then(originalFileBuffer => { | ||
console.log(originalFileBuffer); | ||
// <Buffer 68 69 20 6d 75 6d ... > | ||
}); | ||
// or, for the cool kids | ||
const b64String = await b64.encode(fileBuffer); | ||
const originalFileBuffer = await b64.decode(b64String); | ||
// which is equivalent to this | ||
const b64String = await b64(fileBuffer); | ||
const originalFileBuffer = await b64(b64String); | ||
// Buffers are encoded, strings are decoded | ||
``` | ||
## License | ||
MIT © Luke Childs |
@@ -16,7 +16,8 @@ 'use strict'; | ||
const b64 = (input, opts) => { | ||
if (opts && ['encode', 'decode'].indexOf(opts.method) > -1) { | ||
return b64[opts.method](input, opts); | ||
if (input instanceof Buffer || typeof input === 'string') { | ||
const method = input instanceof Buffer ? 'encode' : 'decode'; | ||
return b64[method](input, opts); | ||
} | ||
return Promise.reject(new Error('opts.method must be \'encode\' or \'decode\'.')); | ||
return Promise.reject(new Error('input must be a buffer or string')); | ||
}; | ||
@@ -23,0 +24,0 @@ |
@@ -9,13 +9,16 @@ import test from 'ava'; | ||
test('b64 calls b64[opts.method]', async t => { | ||
const encodeResult = await b64(values.buffer, { method: 'encode' }); | ||
const decodeResult = await b64(values.base64, { method: 'decode' }); | ||
t.is(encodeResult, values.base64); | ||
t.true(decodeResult instanceof Buffer); | ||
t.is(decodeResult.toString(), values.string); | ||
test('b64 calls b64.encode on buffers', async t => { | ||
const result = await b64(values.buffer); | ||
t.is(result, values.base64); | ||
}); | ||
test('b64 rejects Promise if method is not \'encode\' or \'decode\'', async t => { | ||
const error = await t.throws(b64(values.buffer)); | ||
t.is(error.message, 'opts.method must be \'encode\' or \'decode\'.'); | ||
test('b64 calls b64.decode on strings', async t => { | ||
const result = await b64(values.base64); | ||
t.true(result instanceof Buffer); | ||
t.is(result.toString(), values.string); | ||
}); | ||
test('b64 rejects Promise if input is not a buffer or string', async t => { | ||
const error = await t.throws(b64(0)); | ||
t.is(error.message, 'input must be a buffer or string'); | ||
}); |
9679
8.46%149
2.05%53
194.44%