Skip to content

Commit

Permalink
Replace mz with custom promisified wrappers
Browse files Browse the repository at this point in the history
util.promisify is supported since node v8
https://nodejs.org/api/util.html#util_util_promisify_original

fs.access is supported since 0.11 and recommended for checking file
existence.
https://nodejs.org/api/fs.html#fs_fs_access_path_mode_callback
  • Loading branch information
TrySound committed Jul 1, 2020
1 parent 805413e commit acef7f3
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
25 changes: 19 additions & 6 deletions index.js
Expand Up @@ -2,11 +2,24 @@
* Module dependencies.
*/

const fs = require('fs')
const util = require('util')
const debug = require('debug')('koa-send')
const resolvePath = require('resolve-path')
const createError = require('http-errors')
const assert = require('assert')
const fs = require('mz/fs')

const stat = util.promisify(fs.stat)
const access = util.promisify(fs.access)

async function exists (path) {
try {
await access(path)
return true
} catch (e) {
return false
}
}

const {
normalize,
Expand Down Expand Up @@ -72,12 +85,12 @@ async function send (ctx, path, opts = {}) {

let encodingExt = ''
// serve brotli file when possible otherwise gzipped file when possible
if (ctx.acceptsEncodings('br', 'identity') === 'br' && brotli && (await fs.exists(path + '.br'))) {
if (ctx.acceptsEncodings('br', 'identity') === 'br' && brotli && (await exists(path + '.br'))) {
path = path + '.br'
ctx.set('Content-Encoding', 'br')
ctx.res.removeHeader('Content-Length')
encodingExt = '.br'
} else if (ctx.acceptsEncodings('gzip', 'identity') === 'gzip' && gzip && (await fs.exists(path + '.gz'))) {
} else if (ctx.acceptsEncodings('gzip', 'identity') === 'gzip' && gzip && (await exists(path + '.gz'))) {
path = path + '.gz'
ctx.set('Content-Encoding', 'gzip')
ctx.res.removeHeader('Content-Length')
Expand All @@ -92,7 +105,7 @@ async function send (ctx, path, opts = {}) {
throw new TypeError('option extensions must be array of strings or false')
}
if (!/^\./.exec(ext)) ext = `.${ext}`
if (await fs.exists(`${path}${ext}`)) {
if (await exists(`${path}${ext}`)) {
path = `${path}${ext}`
break
}
Expand All @@ -102,15 +115,15 @@ async function send (ctx, path, opts = {}) {
// stat
let stats
try {
stats = await fs.stat(path)
stats = await stat(path)

// Format the path to serve static file servers
// and not require a trailing slash for directories,
// so that you can do both `/directory` and `/directory/`
if (stats.isDirectory()) {
if (format && index) {
path += `/${index}`
stats = await fs.stat(path)
stats = await stat(path)
} else {
return
}
Expand Down
1 change: 0 additions & 1 deletion package.json
Expand Up @@ -41,7 +41,6 @@
"dependencies": {
"debug": "^4.1.1",
"http-errors": "^1.7.3",
"mz": "^2.7.0",
"resolve-path": "^1.4.0"
},
"scripts": {
Expand Down

0 comments on commit acef7f3

Please sign in to comment.