The problem of css and js loading in nodejs is reported as an error figure. After using fs.readFile, it will be all right. Why?

  node.js, question
//加载静态文件,结果加载css,js的时候会报错
function static_server_file(file,res){
    var rs = fs.createReadStream(file);
    var contents;
    console.log(content_type(file));
    res.writeHead(200,{'Content-Type':content_type(file)});
    
    rs.on('readable',function(){
        var d = rs.read();
        var str;
        if(d){
            if(typeof d == 'string'){
                str = d;
            }else if( typeof d == 'object' && d instanceof Buffer){
                str = d.toString('utf-8');
            }
        }
        if(str){
            if(!contents){
                contents = str;
            }else{
                contents 加= str;
            }
        }
        //res.write(contents);
    });
    rs.on('end',function(){
        //console.log(contents);
        res.write(contents);
        res.end();
    });
    rs.on('error',function(e){
        res.writeHead(404,{'Content-Type':'appalication/json'});
        var out = {
            error:'not found',
            message:file加'not found'
        };
        res.end(JSON.toString(out));
        return;
    })
    
}
//根据文件确定mine类型
function content_type(file){
    var extname = path.extname(file);
    var type;
    switch(extname.toLowerCase()){
        case '.html':
        type = 'text/html';
        break;
        case '.js':
        type = 'text/javascript';
        break;
        case '.css':
        type = 'text/css';
        break;
        case '.jpg':
        type = 'image/jpg';
        break;
        default:type = 'text/plain';
    }
    return type;
}
//这是修改后的版本,加载css,js的时候没有问题,这是为什么
function static_server_file(file,res){

    fs.readFile(file,function(err,data){
        if(err){
            if(err && err.error == 'no_such_album'){
                send_failure(res,404,err);
            }else{
                send_failure(res,500,err);
            }
        }
        
        res.writeHead(200,{'Content-Type':content_type(file)});
        res.write(data);
        res.end();    
    });
}



![图片描述][1]

This function of yoursstatic_server_fileWhy is it so complicated to deal with inside?

function static_server_file(file,res){
 var rs = fs.createReadStream(file);
 var contents;
 console.log(content_type(file));
 
 rs.on('readable',function(){
 res.writeHead(200,{'Content-Type':content_type(file)});
 
 rs.pipe(res);
 });
 
 rs.on('error',function(e){
 res.writeHead(404,{'Content-Type':'appalication/json'});
 var out = {
 error:'not found',
 Message: fileplus 'notfound'
 };
 res.end(JSON.toString(out));
 return;
 })
 bracket

Can this meet your requirements?