Skip to content

Instantly share code, notes, and snippets.

@DanielFGray
Last active April 4, 2017 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DanielFGray/fc496dcfa411e13ddb6b to your computer and use it in GitHub Desktop.
Save DanielFGray/fc496dcfa411e13ddb6b to your computer and use it in GitHub Desktop.
#!/usr/bin/env node
const Promise = require('bluebird')
const http = require('http')
const url = require('url')
const path = require('path')
const fs = require('fs')
const port = process.argv[2] || 6969
const readDir = Promise.promisify(fs.readdir)
const stat = Promise.promisify(fs.stat)
const map = fn => xs => xs.map(fn)
const readDirSortedByTime = dir =>
readDir(dir)
.then(map(file =>
Promise.props({
name: file,
stat: stat(path.join(dir, file)),
}),
))
.then(Promise.all)
.then(stats =>
stats.sort((a, b) =>
a.stat.mtime - b.stat.mtime))
.then(map(x => x.name))
const globals = {
html: '',
}
function parseFiles(files) {
if (! Array.isArray(files)) return
files.forEach((f) => {
if (f.match(/(mp4|webm)$/)) {
globals.html += `<video controls="true" loop="true"><source src="${f}"/></video>'`
} else if (f.match(/(png|gif|jpg|jpeg)$/)) {
globals.html += `<img src="${f}" />`
}
})
}
function printHtml() {
let string = (() => {
let header = ''
// try user headerfile
header = '<!DOCTYPE html><html lang="en"><head><meta name="viewport" content="width=device-width"/><style>body{margin:0;padding:0;background-color:#000;text-align:center;}img,video {max-height:150px;margin:2px;}</style></head><body>'
return header
})()
string += globals.html
string += (() => {
let footer = ''
// try user footerfile
footer = '</body></html>'
return footer
})()
return string
}
function startServer() {
http.createServer((req, res) => {
const filename = path.join(process.cwd(), url.parse(req.url).pathname)
fs.exists(filename, (exists) => {
if (! exists) {
res.writeHead(404, { 'Content-Type': 'text/plain' })
res.write('404 Not Found\n')
res.end()
return
}
if (filename === `${process.cwd()}/`) {
res.writeHead(200)
res.write(printHtml())
res.end()
return
}
if (fs.statSync(filename).isDirectory()) {
res.writeHead(403, { 'Content-Type': 'text/plain' })
res.write('403 Access Denied\n')
res.end()
return
}
fs.readFile(filename, 'binary', (err, file) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' })
res.write(`${err}\n`)
res.end()
return
}
res.writeHead(200)
res.write(file, 'binary')
res.end()
})
})
}).listen(port)
console.log(`Static file server running at\n => http://localhost:${port}/\nCTRL + C to shutdown`)
}
function main(dir) {
readDirSortedByTime(dir)
.then((list) => {
parseFiles(list)
startServer()
})
}
main(process.cwd())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment