Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chapter 6: index.js cannot serve static files this way ! #3

Open
Em-Ant opened this issue Sep 1, 2015 · 3 comments
Open

Chapter 6: index.js cannot serve static files this way ! #3

Em-Ant opened this issue Sep 1, 2015 · 3 comments

Comments

@Em-Ant
Copy link

Em-Ant commented Sep 1, 2015

You should replace the last lines of index.js

...
 } else {
    // Try to send static files
    res.writeHead(200);
    res.end('static file maybe');
  }

with

...
 } else { 
    staticFile(req.url,res); 
  }

The program as is will continue to respond with 'static file maybe' to every request not intercepted by the preceding routing tests.

@elbankster
Copy link

Thank you! It was obvious something was wrong with the code but I couldn't figure it out. I replaced the old code with:

staticFile(req.url);

which does not work. I was stumped. Can you or someone explain why we send two arguments to staticFile when exports.staticFile only asks for one?

@Em-Ant
Copy link
Author

Em-Ant commented Jan 15, 2016

// from ./responseGenerator.js
// (...)
exports.staticFile = function (staticPath) {

\*************** LOOK HERE !! **********************\  
  return function(data, response) {

    var readStream;

    // Fix so routes to /home and /home.html both work.
    data = data.replace(/^(\/home)(.html)?$/i,'$1.html');
    data = '.' + staticPath + data;

    fs.stat(data, function (error, stats) {

      if (error || stats.isDirectory()) {
        return exports.send404(response);
      }

      readStream = fs.createReadStream(data);
      return readStream.pipe(response);
    });
  }
}

When you require the module, then call staticFile(path)

// from index.js
var responder = require('./responseGenerator');
var staticFile = responder.staticFile('/public');

you get a function(data, response), as shown in the previous code sample !!

@iulian-covrig
Copy link

iulian-covrig commented Oct 27, 2016

... } else { staticFile(req.url,res); }
it works, only if you type '/home' or '/home.html' in your browser, otherwise it will give a 404 page. Hope this help. It was the only way I could make it work. Cheers!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants