Take the 2-minute tour ×

In my nodeJS app, I'd like to generate ETags for all the content that I return to the client. I need the ETag to be based off the actual content of the file instead of the date, so that the same file across different node processes has the same ETag.

Right now, I am doing the following:

var fs = require('fs), crypto = require('crypto');
fs.readFile(pathToFile, function(err, buf){
  var eTag = crypto.createHash('md5').update(buf).digest('hex');
  res.writeHead(200, {'ETag': '"' + eTag + '"','Content-Type':contentType});

I am not sure what encodings I should be using for the different crypto functions in order to have a proper system in place. Should I be using something other than hex? Should I get the fs.readFile call to return a hex encoded buffer? If so, will doing so impact the content returned to users?

Best, and Thanks,

share|improve this question
This may help: stackoverflow.com/q/4533 –  Jonathan Lonowski Nov 10 '12 at 23:48
add comment

1 Answer

up vote 1 down vote accepted

You're doing it fine. There is no reason to encode the file in any special format, and using hex for the output is pretty standard. The requirements, loosely speaking, are:

  • the same document should always return the same ETag
  • any changes in the document causes a change in ETag
  • the ETag data should fit neatly into an HTTP header
share|improve this answer
sweet thanks. is there any limit to the size of an input that i can have? if i have a 30MB image file for example (arbitrary number), would that be too much for this system of generation of an ETag? –  thisissami Nov 12 '12 at 6:22
I have no idea how fast the node.js hash implementation is -- you will need to measure it for yourself. If the time to generate the hash is too long, you might think about caching the filename, modification time, and hash somewhere so you don't always have to recompute these things. –  slashingweapon Nov 12 '12 at 15:34
add comment

Your Answer


