Check if a file is binary or ASCII with Node.js?

I'm wondering what would be the best way to check if a file is binary or ASCII with Node.js?

There appears to be two ways not specific to node.js:

  1. Checking the MIME type: How to Check if File is ASCII or Binary in PHP - however this has it's problems, as for instance pre-precessors often don't have a recognised mime type and revert to application/octet-stream when checking them using mime

  2. Via checking the byte size using a stream buffer with How to identify the file content is in ASCII or binary? - which seems quite intensive, and does yet provide a node.js example.

So is there another way already? Perhaps a secret node.js call or module that I don't know about? Or if I have to do this myself, what way would be suggested?

Thanks

ASCII defines characters 0-127, so if a file's entire contents are byte values in that range then it can be considered an ASCII file.

function fileIsAscii(filename, callback) {
  // Read the file with no encoding for raw buffer access.
  require('fs').readFile(filename, function(err, buf) {
    if (err) throw err;
    var isAscii = true;
    for (var i=0, len=buf.length; i<len; i++) {
      if (buf[i] > 127) { isAscii=false; break; }
    }
    callback(isAscii); // true iff all octets are in [0, 127].
  });
}
fileIsAscii('/usr/share/dict/words', function(x){/* x === true */});
fileIsAscii('/bin/ls', function(x){/* x === false */});

If performance is critical then consider writing a custom C++ function per your linked answer.

Thanks to the comments on this question by David Schwartz, I created istextorbinary to solve this problem.