title: Node.js - File System get file type, solution around year 2012
body: <p>I need to get the file type of a file with the help of node.js to set the content type. I know I can easily check the file extension but I've also got files without extension which should have the content type <code>image/png</code>, <code>text/html</code> aso.</p>
  
  <p>This is my code (I know it doesn't make much sense but that's the base I need):</p>
  
  <pre><code>var http = require("http"),
      fs = require("fs");
  http.createServer(function(req, res) {
      var data = "";
      try {
          /*
           * Do not use this code!
           * It's not async and it has a security issue.
           * The code style is also bad.
           */
          data = fs.readFileSync("/home/path/to/folder" + req.url);
          var type = "???"; // how to get the file type??
          res.writeHead(200, {"Content-Type": type});
      } catch(e) {
          data = "404 Not Found";
          res.writeHead(404, {"Content-Type": "text/plain"});
      }
      res.write(data);
      res.end();
  }).listen(7000);
  </code></pre>
  
  <p>I haven't found a function for that in the <a href="http://nodejs.org/api/fs.html" rel="noreferrer">API</a> so I would be happy if anyone can tell me how to do it.</p>