Skip to content

Instantly share code, notes, and snippets.

@colthreepv
Last active December 26, 2015 12:59
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 colthreepv/7155518 to your computer and use it in GitHub Desktop.
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
/**
* 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);
{
"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