2013-09-01 41 views
6

我的目錄是這樣的:Node.js的__dirname沒有定義

/config.json , /server.js , /staticFiles/welcome.html

運行server.js給出了錯誤:

app.use(express.static(_dirname + "/staticFiles")); ^ ReferenceError: _dirname is not defined

我Server.js:

//------------Server------------- 

var fs = require("fs"); 
var config = JSON.parse(fs.readFileSync("./config.json")); 

console.log("Server UP and running.."); 

var host = config.host; 
var port = config.port; 
var express = require("express"); 

var app = express.createServer(); 



//---------Application---------------- 

app.use(app.router); 
app.use(express.static(_dirname + "/staticFiles")); 

app.get("/", function(request,response){ 

response.send("<h1>"/" of TrimServer</h1>"); 

}); 

app.listen(port,host); 
console.log("Listening on Port -->",port); 


//--------------End------------------- 
+0

快速搜索發現此錯誤多個匹配。 https://groups.google.com/forum/m/#!msg/nodejs/K4vhAC5yXm4/qFfGK0WCgSYJ – WiredPrairie

回答

23

你是使用一個下劃線,而這個變量實際上在開頭有兩個下劃線: http://nodejs.org/docs/latest/api/globals.html#globals_dirname

所以使用的

app.use(express.static(__dirname + "/staticFiles")); 

代替

app.use(express.static(_dirname + "/staticFiles")); 
+0

@ Cromax謝謝.. – ManishS

+0

感謝Cromax。 @ManishS,您可以將其標記爲正確的答案 –

1

使用__dirname代替_dirname的(缺少代碼中的一個下劃線)

相關問題