Node.js __dirname not defined

My directory is as follows:

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

Running server.js gives an error:

app.use (express.static (_dirname + "/ staticFiles")); ^ ReferenceError: _dirname 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------------------- 
+10
source share
3 answers

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

So use

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

instead

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

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

+2
source

Use __dirname instead of _dirname (there is no underscore in your code).

0
source

Source: https://habr.com/ru/post/952915/


All Articles