Last active
December 26, 2015 12:59
-
-
Save colthreepv/7155518 to your computer and use it in GitHub Desktop.
tail -f webserver version, using chunked responses (HTTP 1.1) http://goo.gl/4VuKS6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* tail -f webserver version, using chunked responses (HTTP 1.1) | |
* slides: http://goo.gl/4VuKS6 | |
*/ | |
var fs = require('fs'), | |
util = require('util'), | |
http = require('http'); | |
http.createServer(function (req, res) { | |
fs.stat(req.url, function (err, stats) { | |
var readBytes = 0, | |
streamFile = function (filename, outputStream, isWatching) { | |
var watchFn = function () { | |
var fileToStream = fs.createReadStream(filename, { start: readBytes, encoding: 'utf8' }); | |
fileToStream.on('data', function (chunk) { | |
readBytes += chunk.length; | |
outputStream.write(chunk); | |
}); | |
return fileToStream; | |
}; | |
if (isWatching) { | |
return watchFn; | |
} else { | |
return watchFn(null, filename); | |
} | |
}; | |
if (err) { | |
res.statusCode = 404; | |
return res.end(); | |
} | |
if (!stats.isFile()) { | |
res.statusCode = 412; | |
return res.end(); | |
} else { | |
res.statusCode = 200; | |
streamFile(req.url, res) | |
.on('end', function () { | |
console.log('GET: ' + req.url); | |
fs.watch(req.url, streamFile(req.url, res, true)); | |
}); | |
} | |
}); | |
}).listen(2610); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "nodejs-tail", | |
"version": "0.1.0", | |
"description": "a tail -f version coded in node.js", | |
"main": "chunked.js", | |
"repository": { | |
"type": "git", | |
"url": "github.com:7155518.git" | |
}, | |
"keywords": [ | |
"nodejs", | |
"tail", | |
"chunked" | |
], | |
"author": "mrgamer", | |
"license": "MIT", | |
"dependencies": { | |
"express": "~3.4.0", | |
"async": ">=0.2.0", | |
"docular": "https://github.com/TopCS/docular/tarball/master" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment