2017-07-03 32 views
1

通過Node動作創建一個聊天應用程序,並在運行server.js時出現以下錯誤: function serveStatic(response,cache,absPath) ^^^^^^^^ SyntaxError:意外的標記函數 at Object.exports.runInThisContext(vm.js:73:16) at Module._compile(module.js:543:28) at Object.Module._extensions..js(module.js :module.js:488:32) at tryModuleLoad(module.js:447:12) at Function.Module._load(module.js:439:3) at Module在Module.load(module.js:488:32) .runMain(module.js:605:10) at run( bootstrap_node.js:418:7) 在啓動時(bootstrap_node.js:139:9) 在bootstrap_node.js:533:3SyntaxError:意外的令牌功能

這裏是Server.js代碼:

var http=require('http');        
var fs=require('fs');         
var path=require('path');             
var path= require('mime');        
var cache={}; 




var server=http.createServer(function(request,response) 
{ 
    var filePath=false; 
    if(request.url=='/') 
    { 
     filePath= public/index.html; 
    } 
    else 
    { 
     'public' + request.url; 
    } 

    var absPath= './'+filePath; 
    serveStatic(response,cache,absPath); 
}); 

server.listen(3000,function() 
{ 

console.log('Server listening to the port :3000'); 

}); 




function send404 (response) 
{ 
    response.writeHead(404,{'Content-Type' :'text/plain'}); 
    response.write('Error 404: resource not found'); 
    response.end(); 
} 




function sendFile(response,filePath,fileContents) 
{ 
    response.wrieHead(200, 
     {"content-type":mime.lookup(filePath)}) 

     }; 
     response.end(fileContents); 

} 



function serveStatic(response,cache,absPath) 
{ 
    if(cache[absPath]) 
    { 
    sendFile(response,absPath,cache[absPath]); 
    } 
    else 
    { 
     if(fs.exists(absPath, function(exists))) 
     { 
     if(exists) 
     { 
      fs.readFile(absPath,function(err,data)) 
      { 
      if(err) 

      { 
      send404(response); 
      } 
      else 
      { 
      cache[absPath]=data; 
      sendFile(response,absPath,data); 
      } 
      }); 

     } 
     else 
     { 
     send404(response); 
     } 
     }); 
    } 
} 
+2

'filePath = public/index.html;'缺少引號和''public'+ request.url;'是一個沒有任何操作的無效操作... –

+0

@AlexK。 ,現在在這個地方得到了這些缺失的引號,仍然是上面顯示的錯誤 –

+0

,您似乎還有一些額外的隨機'}'和一個隨機') - 正確縮進代碼以查看問題 –

回答

0

你必須這裏額外的括號:

function sendFile(response,filePath,fileContents) 
{ 
    response.wrieHead(200, 
     {"content-type":mime.lookup(filePath)}) 

     }; 
     response.end(fileContents); 

} 

應該修改這種方式:

function sendFile(response, filePath, fileContents) 
{ 
    response.wrieHead(200, { 
     "content-type": mime.lookup(filePath) 
    }); 
    response.end(fileContents); 

} 

然後你的錯誤將被解僱。

+0

謝謝,它有幫助,但除此之外,還有其他幾個語法錯誤,現在運行良好,服務器正在偵聽端口:3000 :) –