title: My First Node.js server : Failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING
body: <p>The following server is supposed to :</p>
  
  <p>CASE #1 : serve <code>mysitename.html</code> if the request is <code>http://localhost:8080</code></p>
  
  <p>CASE #2 : serve the relevant file if the request is e.g. <code>http://localhost:8080/mysitename.html</code></p>
  
  <p>CASE #3 send me an email if the request is <code>http://localhost:8080/contactform?name=..&amp;..&amp;...etc.</code></p>
  
  <p>If I visit <code>http://localhost:8080/mysitename.html</code>everything works fine. <code>mysitename.html</code> is loaded and then all subsequent content (.js, .css, .png etc.) is loaded through it.</p>
  
  <p><strong>PROBLEM :</strong> However, if I visit <code>http://localhost:8080</code>, the following happens :</p>
  
  <ul>
  <li>I get a <strong>Failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING</strong> error on the browser's (Chrome) console.</li>
  <li>`mysitename.html' appears corrupted on the client. Parts of the DOM are missing and when I try to view the source page, it just hangs and never actually loads. Loading only part of the DOM is weird given that all DOM elements of this file are static/hardcoded.</li>
  <li>What's confusing is that the rest of the content (.js, .css etc..) is loaded but nothing actually shows because of the corrupted .html. Is it possible that CASE#1 is interrupted by CASE#2 that follows right after it? What exactly am I doing wrong ?</li>
  </ul>
  
  <p><em>CASE#2 initially had an error which was causing an infinite loop found by Johnny Estilles (see his answer below). This has since been fixed but the issues mentioned above now occur.</em></p>
  
  <p><strong>server.js</strong></p>
  
  <pre><code>// setting up email handler
  var nodemailer = require('nodemailer');
  var emailHandlerService = 'Gmail';
  var emailHandlerAddress = ******;
  var emailHandlerPassword = ******;
  var transporter = nodemailer.createTransport({
      service: emailHandlerService,
      auth: {
          user: emailHandlerAddress,
          pass: emailHandlerPassword
      }
  });
  
  // setting up http server
  var http = require('http');
  var fs = require('fs');
  var url = require("url");
  var path = require("path");
  var rootDir = __dirname + "/public";
  
  var mimeTypes = {
      "html": "text/html",
      "jpeg": "image/jpeg",
      "jpg": "image/jpeg",
      "png": "image/png",
  
      /* Even though the js mime type is set as well, scripts are still sent 
      as "text/plain" according to the Chrome console. Why is that ? */
      "js": "application/javascript",
  
      "css": "text/css",
      "ico": "image/ico"
  };
  
  // initializing server
  var httpServer = http.createServer(function (request, response)
  {
      // CASE #1
      // if the user is on http://localhost:8080, load public/mysitename.html
      if (request.url === "/")
      {
          fs.readFile('public/mysitename.html', function (err, html) 
          {
              if (err)
              {
                  response.writeHead(200, {'Content-Type': 'text/plain'});
                  response.write('404 Not Found\n');
                  throw (err);
              }
              else
              {
                  response.writeHeader(200, {"Content-Type": "text/html"});  
                  response.write(html); 
              }
          });
      }
  
  
  
  
      // CASE #2
      // else if this is a contact form data request
      // forward the data to my email (I'll make a more precise Regex for the request)
  
      else if (/contactform/.test(request.url))
      {
          var parsedURL = url.parse(request.url, true);
          var name  = parsedURL.query.name;
          var email  = parsedURL.query.email;
          var subject  = parsedURL.query.subject;
          var enquiry  = parsedURL.query.enquiry;
          var browser = parsedURL.query.browsername + " " + 
                        parsedURL.query.browserversion;
  
          transporter.sendMail({
              from: emailHandlerAddress,
              to: emailHandlerAddress,
              subject: subject,
              text: "|| NAME = " + name + " || EMAIL = " + 
                     email + " || BROWSER = "  + browser + " || DEVICE = " + 
                     parsedURL.query.device + " || ENQUIRY = " + enquiry
          });
  
          response.end(JSON.stringify(parsedURL.query));
      }
  
  
  
  
      // CASE #3
      // if none of the above is true then this is a request to serve static files
      else
      {
          var pathname = url.parse(request.url).pathname;
          var filename = path.join(rootDir, pathname);
  
          fs.exists(filename, function (exists) 
          {
              if (!exists) 
              {
                  fs.readFile('public/404.html', function (err, html) 
                  {
                      if (err)
                      {
                          response.writeHead(200, {'Content-Type': 'text/plain'});
                          response.write('404 Not Found\n');
                          throw (err);
                      }
                      else
                      {
                          response.writeHeader(200, {"Content-Type": "text/html"});  
                          response.write(html); 
                      }
                      response.end();
                  });
              }
              else
              {
                      var requestedFileExtension = path.extname(filename).split(".")[1];
                  var mimeType = mimeTypes[requestedFileExtension] || 'text/plain';
  
                  // as I noted above, this doesn't seem to have any effect 
                  // for my .js files
                  response.writeHead(200, mimeType);
  
                  var fileStream = fs.createReadStream(filename);
                  fileStream.pipe(response);
              }
          });
      }
  }).listen(8080);
  </code></pre>