R
R
Roman2015-02-06 03:13:57
Node.js
Roman, 2015-02-06 03:13:57

How to transfer static resources to the client?

There is this code

<link href="css/custom-theme/jquery-ui-1.9.2.custom.css" rel="stylesheet">
    <script src="js/jquery-1.8.3.js"></script>
    <script src="js/jquery-ui-1.9.2.custom.js"></script>
    <script src="js/window.js"></script>

http.createServer(function (request, response) {
  var path = url.parse(request.url).pathname;
  
  switch (path) {

    case '/':
      sendPage(response);
      break;
    default:
      var fileOpt = "utf8";
      if (path.substring(path.length - 3) == "jpg")
        fileOpt = "binary";

      fs.readFile("."+path, fileOpt, function(err, data) {
        if (err) {
          console.log(err);
          response.writeHead("404", {"Content-Type": "text/plain"})
          response.write('File not found!');
        } else {
          console.log(path);
          console.log(fileOpt);
          console.log(getMIME(path));
          response.writeHead("200", getMIME(path));
          response.write(data);
          response.end;
        }
      });
      break;
  }
}).listen(8888);

log outputs the following:
/css/custom-theme/jquery-ui-1.9.2.custom.css
utf8
{ 'Content-Type': 'text/css' }
/js/jquery-1.8.3.js
utf8
{ 'Content-Type': 'application/x-javascript' }
/js/jquery-ui-1.9.2.custom.js
utf8
{ 'Content-Type': 'application/x-javascript' }
/js/window.js
utf8
{ 'Content-Type': 'application/x-javascript' }
/img/2.jpg
binary
{ 'Content-Type': 'image/jpeg' }
/img/3.jpg
binary
{ 'Content-Type': 'image/jpeg' }
/img/4.jpg
binary
{ 'Content-Type': 'image/jpeg' }
/img/5.jpg
binary
{ 'Content-Type': 'image/jpeg' }

html is given normally, then the browser asks for resources: css, js scripts, pictures. And here is the very "NIAL"!
contenttypes are correctly defined, the data itself was output to the log - it is also there, and the browser is waiting for the data and does not wait for them in the end. What is the problem, how does it work?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
kazmiruk, 2015-02-06
@losaped

You don't say that the answer is complete. You need to call response.end(); at the end, and you have response.end;

A
Alexander Prozorov, 2015-02-06
@Staltec

1. Your decision to serve static content is a potential security hole. This approach allows you to read files outside the document root if you specify a path with a jump to the parent directory ('../').
2. Use serve-static ( https://github.com/expressjs/serve-static) as an option or Express 4.
3. In general, static should be given to those that do it best. Use Nginx for this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question