Skip to content

Commit

Permalink
Use bluebird instead of async/await (much faster runtime)
Browse files Browse the repository at this point in the history
  • Loading branch information
leo committed Feb 14, 2017
1 parent d6d702b commit 90a355d
Show file tree
Hide file tree
Showing 6 changed files with 30 additions and 42 deletions.
17 changes: 0 additions & 17 deletions bin/serve.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,13 @@
#!/usr/bin/env node

// Native
const path = require('path')

// Packages
const asyncToGen = require('async-to-gen/register')
const updateNotifier = require('update-notifier')
const {red} = require('chalk')
const nodeVersion = require('node-version')
const isAsyncSupported = require('is-async-supported')

// Ours
const pkg = require('../package')

// Support for keywords "async" and "await"
if (!isAsyncSupported()) {
const packageDir = path.basename(path.join(__dirname, '..'))
const modulesDir = path.join(packageDir, 'node_modules')

asyncToGen({
excludes: new RegExp(`.*${modulesDir}.*`),
sourceMaps: false
})
}

// Throw an error if node version is too low
if (nodeVersion.major < 6) {
console.error(`${red('Error!')} Serve requires at least version 6 of Node. Please upgrade!`)
Expand All @@ -36,5 +20,4 @@ if (!process.env.NOW && pkg.dist) {
updateNotifier({pkg}).notify()
}

// Load package core with async/await support
require('../lib')
13 changes: 7 additions & 6 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const micro = require('micro')
const args = require('args')
const compress = require('micro-compress')
const detect = require('detect-port')
const {coroutine} = require('bluebird')

// Ours
const listening = require('./listening')
Expand Down Expand Up @@ -40,9 +41,9 @@ if (flags.ignore && flags.ignore.length > 0) {
ignoredFiles = ignoredFiles.concat(flags.ignore.split(','))
}

const handler = async (req, res) => {
await serverHandler(req, res, flags, current, ignoredFiles)
}
const handler = coroutine(function * (req, res) {
yield serverHandler(req, res, flags, current, ignoredFiles)
})

const server = flags.unzipped ? micro(handler) : micro(compress(handler))
let port = flags.port
Expand All @@ -59,7 +60,7 @@ detect(port).then(open => {
}
}

server.listen(port, async () => {
return await listening(server, current, inUse)
})
server.listen(port, coroutine(function * () {
yield listening(server, current, inUse)
}))
})
17 changes: 10 additions & 7 deletions lib/listening.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,18 @@ const ip = require('ip')
const pathType = require('path-type')
const chalk = require('chalk')
const boxen = require('boxen')
const {coroutine} = require('bluebird')

const copyToClipboard = async text => {
const copyToClipboard = coroutine(function * (text) {
try {
await copy(text)
yield copy(text)
return true
} catch (err) {
return false
}
}
})

module.exports = async (server, current, inUse) => {
module.exports = coroutine(function * (server, current, inUse) {
const details = server.address()
const ipAddress = ip.address()
const url = `http://${ipAddress}:${details.port}`
Expand All @@ -26,7 +27,9 @@ module.exports = async (server, current, inUse) => {
process.exit(0)
})

if (!await pathType.dir(current)) {
const isDir = yield pathType.dir(current)

if (!isDir) {
console.error(chalk.red('Specified directory doesn\'t exist!'))
process.exit(1)
}
Expand All @@ -47,7 +50,7 @@ module.exports = async (server, current, inUse) => {
message += `- ${chalk.bold('On Your Network: ')} ${url}\n\n`

if (isTTY) {
const copied = await copyToClipboard(localURL)
const copied = yield copyToClipboard(localURL)

if (copied) {
message += `${chalk.grey('Copied local address to clipboard!')}`
Expand All @@ -60,4 +63,4 @@ module.exports = async (server, current, inUse) => {
margin: 1
}))
}
}
})
11 changes: 6 additions & 5 deletions lib/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@ const path = require('path')
const pathType = require('path-type')
const filesize = require('filesize')
const fs = require('fs-promise')
const {coroutine} = require('bluebird')

// Ours
const prepareView = require('./view')

module.exports = async (port, current, dir, ignoredFiles) => {
module.exports = coroutine(function * (port, current, dir, ignoredFiles) {
let files = []
const subPath = path.relative(current, dir)

Expand All @@ -18,7 +19,7 @@ module.exports = async (port, current, dir, ignoredFiles) => {
}

try {
files = await fs.readdir(dir)
files = yield fs.readdir(dir)
} catch (err) {
throw err
}
Expand All @@ -30,15 +31,15 @@ module.exports = async (port, current, dir, ignoredFiles) => {

details.relative = path.join(subPath, details.base)

if (await pathType.dir(filePath)) {
if (yield pathType.dir(filePath)) {
details.base += '/'
} else {
details.ext = details.ext.split('.')[1] || 'txt'

let fileStats

try {
fileStats = await fs.stat(filePath)
fileStats = yield fs.stat(filePath)
} catch (err) {
throw err
}
Expand Down Expand Up @@ -105,4 +106,4 @@ module.exports = async (port, current, dir, ignoredFiles) => {
}

return render(details)
}
})
11 changes: 6 additions & 5 deletions lib/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@ const fs = require('fs-promise')
const pathType = require('path-type')
const mime = require('mime-types')
const stream = require('send')
const {coroutine} = require('bluebird')

// Ours
const renderDirectory = require('./render')

module.exports = async (req, res, flags, current, ignoredFiles) => {
module.exports = coroutine(function * (req, res, flags, current, ignoredFiles) {
const headers = {}

if (flags.cors) {
Expand Down Expand Up @@ -62,7 +63,7 @@ module.exports = async (req, res, flags, current, ignoredFiles) => {

try {
const custom404Path = path.join(current, '/404.html')
notFoundResponse = await fs.readFile(custom404Path, 'utf-8')
notFoundResponse = yield fs.readFile(custom404Path, 'utf-8')
} catch (err) {}

if (!relatedExists && flags.single === undefined) {
Expand All @@ -76,7 +77,7 @@ module.exports = async (req, res, flags, current, ignoredFiles) => {
}

// Check if directory
if (relatedExists && await pathType.dir(related)) {
if (relatedExists && pathType.dirSync(related)) {
// Normalize path to trailing slash
// Otherwise problems like #70 will occur
const url = parse(req.url)
Expand All @@ -98,7 +99,7 @@ module.exports = async (req, res, flags, current, ignoredFiles) => {
if (!fs.existsSync(indexPath)) {
// Try to render the current directory's content
const port = flags.port || req.socket.localPort
const renderedDir = await renderDirectory(port, current, related, ignoredFiles)
const renderedDir = yield renderDirectory(port, current, related, ignoredFiles)

// If it works, send the directory listing to the user
if (renderedDir) {
Expand Down Expand Up @@ -129,4 +130,4 @@ module.exports = async (req, res, flags, current, ignoredFiles) => {
return stream(req, related, Object.assign({
dotfiles: 'allow'
}, streamOptions)).pipe(res)
}
})
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@
},
"dependencies": {
"args": "2.3.0",
"async-to-gen": "1.3.2",
"basic-auth": "1.1.0",
"bluebird": "3.4.7",
"boxen": "1.0.0",
"chalk": "1.1.3",
"copy-paste": "1.3.0",
Expand All @@ -61,7 +61,6 @@
"fs-promise": "2.0.0",
"handlebars": "4.0.6",
"ip": "1.1.4",
"is-async-supported": "1.2.0",
"micro": "7.0.6",
"micro-compress": "1.0.0",
"mime-types": "2.1.14",
Expand Down

0 comments on commit 90a355d

Please sign in to comment.