javascript Node.js __dirname 未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18556613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:22:57  来源:igfitidea点击:

Node.js __dirname not defined

javascriptnode.js

提问by ManishS

My directory look like this:

我的目录是这样的:

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

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

Running server.js gives error:

运行 server.js 给出错误:

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

app.use(express.static(_dirname + "/staticFiles")); ^ 参考错误:_dirname 未定义

My Server.js:

我的 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-------------------

回答by Didatus

You are using one underscore while this variable actually has two underscores at the beginning: http://nodejs.org/docs/latest/api/globals.html#globals_dirname

您使用的是一个下划线,而此变量实际上在开头有两个下划线:http: //nodejs.org/docs/latest/api/globals.html#globals_dirname

So use

所以用

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

instead of

代替

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

回答by Saket Sinha

use __dirname instead of _dirname (Missing one underscore in your code)

使用 __dirname 而不是 _dirname (代码中缺少一个下划线)

回答by Chandra Pant

Use __dirnameinstead of _dirname(You are missing one underscore in your code).

使用__dirname而不是_dirname(您的代码中缺少一个下划线)。