2013-09-01 31 views
6

thư mục My trông như thế này:Node.js __dirname không được định nghĩa

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

Chạy server.js cho lỗi:

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

My 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

Một tìm kiếm nhanh chóng tìm thấy nhiều trận cho lỗi này. https://groups.google.com/forum/m/#!msg/nodejs/K4vhAC5yXm4/qFfGK0WCgSYJ – WiredPrairie

Trả lời

23

Bạn đang sử dụng một dấu gạch dưới trong khi biến này thực sự có hai dấu gạch dưới ở đầu: http://nodejs.org/docs/latest/api/globals.html#globals_dirname

Vì vậy, sử dụng

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

thay vì

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

@ Cromax Thanks .. – ManishS

+0

Cảm ơn Cromax. @ ManishS, bạn có thể đánh dấu đây là câu trả lời đúng –

1

__dirname sử dụng thay vì _dirname (Thiếu một dấu gạch dưới trong mã của bạn)

Các vấn đề liên quan