socket.io and differents folders — solution found

前端 未结 5 1490
轮回少年
轮回少年 2020-12-18 09:39

I\'m new to socket.io and i already have a problem, minor i think. I have installed node.js properly and socket.io too with npm. Then just for testing i cut and paste a sam

相关标签:
5条回答
  • 2020-12-18 10:03

    And you must made fs.readFile wrapped by a closure, otherwise some file (especially the last file) will be read more than once, and others will not be read at all. And the contentTypewill not be set as you wish. This is because of the callback strategy used by fs.readFile. The problem does not appear when the html file just load one external file, but as the external files(css, js, png) loaded more than one it will appear as i pointed out above. (I came upoon this by myself)

    So your code should make a little change as follows:

    ;(function (filename, contentType) {
    
        fs.readFile(filename, function(err, file) {
            // do the left stuff here
        });
    
    }(filename, contentType)); 
    
    0 讨论(0)
  • 2020-12-18 10:11

    Thank you so much! This solved my problem!! And I changed the switch to following code:

    var extname = path.extname(filePath);
    var contentTypesByExtention = {
      'html': 'text/html',
      'js':   'text/javascript',
      'css':  'text/css'
    };
    var contentType = contentTypesByExtention[extname] || 'text/plain';
    

    It may be easier to maintain :)

    0 讨论(0)
  • 2020-12-18 10:16

    Only that solves:

    function handler (request, response) {
        var file = __dirname + (request.url == '/' ? '/index.html' : request.url);
        fs.readFile(file, function(error, data) {
            if (error) {
                response.writeHead(500);
                return response.end('Error loading index.html');
            }
            response.writeHead(200);
            response.end(data, 'utf-8');
        });
    }
    
    0 讨论(0)
  • 2020-12-18 10:21

    that's what i need! thank you! and we'll add one code line a top of

    server.js

    var app = require('http').createServer(handler)
      , io = require('socket.io').listen(app)
      , fs = require('fs')
      **, path = require('path')**
    
    0 讨论(0)
  • 2020-12-18 10:24

    You can use mime module as well:

    var mime = require('mime')
      , content_type = mime.lookup(filePath);
    
    // handle the request here ...
    
    response.setHeader('Content-Type', content_type);
    response.writeHead(200);
    response.end(data);
    
    0 讨论(0)
提交回复
热议问题