Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: __dirname value?

Tags:

typescript

My folder structure is like this:

app
└─ tsFolder
   └─ XX.ts

Code in XX.ts file:

var __dirname: string;
console.log("__dirname: " + __dirname); // the output is undefined.

I have tried it: by comment out the code var __dirname: string;, the value of __dirname is: ...../app insead of pointing to the current folder like ...../app/tsFolder.

Can anyone explain it?

like image 281
Ng2-Fun Avatar asked Mar 30 '16 17:03

Ng2-Fun


People also ask

What is the value of __ Dirname?

__dirname: It is a local variable that returns the directory name of the current module. It returns the folder path of the current JavaScript file. It returns the name the of current working directory.

Why __ Dirname is not defined?

The __dirname or __filename global variables are not available in ECMAScript module files. To solve the "__dirname is not defined in ES module scope" error, import and use the dirname() method from the path module. The dirname method takes a path as a parameter and returns the directory name of the path. Copied!

What does __ Dirname mean in node?

__dirname is an environment variable that tells you the absolute path of the directory containing the currently executing file.

What is dirname in path?

The path. dirname() method returns the directories of a file path.


2 Answers

Just run

npm install --save-dev @types/node

And if that doesn't work on its own, add

"types": ["node"]

to your tsconfig.json's compilerOptions field.

like image 111
Daniel Rosenwasser Avatar answered Sep 23 '22 02:09

Daniel Rosenwasser


I assume you refer to NodeJS global variable __dirname.

If it points to the ..../app it means that your XX.ts is compiled to the ..../app folder. And when the resulting js file is run: __dirname points to its (js file) location.

And of course, you should not declare new var __dirname.

Instead, either use NodeJS typings or just declare it manually like this:

declare var __dirname;
like image 40
Amid Avatar answered Sep 22 '22 02:09

Amid