Skip to content

Commit

Permalink
Switch to a more idiomatic api
Browse files Browse the repository at this point in the history
Fixes #5
LinusU committed May 22, 2016
1 parent f40e3ce commit ade964a
Showing 3 changed files with 33 additions and 9 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -21,7 +21,7 @@ md5File('LICENSE.md', (err, hash) => {
})

/* Sync usage */
const hash = md5File('LICENSE.md')
const hash = md5File.sync('LICENSE.md')
console.log(`The MD5 sum of LICENSE.md is: ${hash}`)
```

@@ -33,7 +33,7 @@ Asynchronously get the MD5-sum of the file at `filepath`.

The callback `cb` will be called with `(err: Error, hash: string)`.

### `md5File(filepath: string) => string`
### `md5File.sync(filepath: string) => string`

Synchronously get the MD5-sum of the file at `filepath`.

9 changes: 5 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
@@ -24,10 +24,8 @@ function md5FileSync (filename) {
return hash.digest('hex')
}

module.exports = function (filename, cb) {
if (typeof cb !== 'function') {
return md5FileSync(filename)
}
function md5File (filename, cb) {
if (typeof cb !== 'function') throw new TypeError('Argument cb must be a function')

var output = crypto.createHash('md5')
var input = fs.createReadStream(filename)
@@ -42,3 +40,6 @@ module.exports = function (filename, cb) {

input.pipe(output)
}

module.exports = md5File
module.exports.sync = md5FileSync
29 changes: 26 additions & 3 deletions test.js
Original file line number Diff line number Diff line change
@@ -8,6 +8,8 @@ var assert = require('assert')
var filename = 'LICENSE.md'
var preCheckedSum = '687d0001c49a6315989af72c0325dff3'

function noop () {}

describe('md5File', function () {
it('works asynchronously', function (done) {
md5File(filename, function (err, hash) {
@@ -19,9 +21,7 @@ describe('md5File', function () {
})

it('works synchronously', function () {
var actual = md5File(filename)

assert.equal(actual, preCheckedSum)
assert.equal(md5File.sync(filename), preCheckedSum)
})

it('has proper error handling', function (done) {
@@ -32,4 +32,27 @@ describe('md5File', function () {
done()
})
})

it('requires a callback', function () {
assert.throws(function () { md5File(filename) }, TypeError)
})

it('only accepts strings and buffers', function () {
var invalidValues = [
[],
{},
123,
null,
undefined
]

if (typeof Symbol !== 'undefined') {
invalidValues.push(Symbol('test'))
}

invalidValues.forEach(function (value) {
assert.throws(function () { md5File.sync(value) }, TypeError)
assert.throws(function () { md5File(value, noop) }, TypeError)
})
})
})

0 comments on commit ade964a

Please sign in to comment.