Node.js - getting the current file name

How to get current file name, function name and line number?

I want to use it for logging / debugging purposes equivalent to __FILE__ , __LINE__ in c

+70
Jan 07 '13 at 18:03
source share
10 answers
 console.log(__dirname) console.log(arguments.callee.toString()) 
-four
Jan 07 '13 at 18:09
source share

Node.js provides a standard API for this: Path .

Getting the name of the current script is easy:

 var path = require('path'); var scriptName = path.basename(__filename); 
+171
Feb 04 '15 at 10:31
source share

inside the module, you can do any of the following to get the full path with the file name

 this.filename; module.filename; __filename; 

If you just want the actual name without a path or extension, you can do something like this.

 module.filename.slice(__filename.lastIndexOf(path.sep)+1, module.filename.length -3); 
+39
Sep 22 '13 at 10:02
source share

To get only the file name. There is no additional module just:

 // abc.js console.log(__filename.slice(__dirname.length + 1)); // abc console.log(__filename.slice(__dirname.length + 1, -3)); 
+22
Aug 6 '15 at 12:45
source share
 'use strict'; const scriptName = __filename.split(/[\\/]/).pop(); 

explanation

 console.log(__filename); // 'F:\__Storage__\Workspace\StackOverflow\yourScript.js' const parts = __filename.split(/[\\/]/); console.log(parts); /* * [ 'F:', * '__Storage__', * 'Workspace', * 'StackOverflow', * 'yourScript.js' ] * **/ 

Here we use the split function with regex as the first parameter.
The regular expression that we want to use for the delimiter is [\/] (split by / or \ ), but the / character needs to be escaped to distinguish it from the regular expression terminator / , so /[\\/]/ .

 const scriptName = __filename.split(/[\\/]/).pop(); // Remove the last array element console.log(scriptName); // 'yourScript.js' 

Do not use this

You really should use path.basename instead (first documented in Node.js v0.1.25 ), because it handles all corner cases that you don't want to know about file names with slashes inside (for example, a file named " foo \ bar "on Unix). See path response above .

+17
Aug 31 '15 at 11:41
source share

You can also see console-plus . This adds the file name and linenumber to any text logging and has different colors for .log, .info and .error.

+3
Jan 08 '13 at 7:26
source share

Well, I wanted to use the file name as a tag for the registrar, so the most direct and what I need is the following:

 __filename.substring(__dirname.length + 1, __filename.lastIndexOf(".")) 
0
Apr 03 '17 at 18:58
source share

I use the following regex:

 ([^\\/]+?)(?:\.[^\.\\/]*)?$ 

Working from the end of line $ , is there an optional group that cannot be captured for a possible extension (?:\.[^\.\\/]*)? preceded by an unwanted capture group for anything but directory separators \/ . The file name group is inanimate, allowing the next group that does not contain a capture to abandon a possible extension.

The implementation will refer to the first and only capture group [1] :

 var name = __filename.match(/([^\\/]+?)(?:\.[^\.\\/]*)?$/)[1]; 

Group capturing a file name with an inanimate / lazy specifier

 ([^\\/]+?) ^ lazy 

An optional extension group that should be discarded bound $ to the end of the line

  (?:\.[^\.\\/]*)?$ ^^ ^ non-capture optional 

 var regex = /([^\\/]+?)(?:\.[^\.\\/]*)?$/; [ ["abc.js", "abc"], ["/tmp/test/../lib/stuff.js", "stuff"], ["c:\\temp\\test\\..\\lib\\stuff.js", "stuff"], ["./abc/def.js", "def"], [".\\abc\\win.js", "win"], ["./lib/my-module.js", "my-module"], [".\\lib/my-dotless", "my-dotless"], ["..///lib/..\\\\.//..dots&seps..", "..dots&seps."], ["trailing-dots...js", "trailing-dots.."] ].forEach( test => { var name = test[0].match(regex)[1]; var result = test[0] + " => " + test[1] + " # " + (name === test[1] ? "Passed" : "Failed"); console.log(result); }); 

Evaluation courtesy of https://regex101.com

0
Aug 02 '17 at 2:50 on
source share

I know this was a long time ago, but I did __filename.split('\\').pop() . This will get the full path to the file name, split it by \ then get the last index that will be your file name.

0
Jul 10 '18 at 10:20
source share

You can use this function to get the file name:

 /** * @description * get file name from path * @param {string} path path to get file name * @returns {string} file name * @example * getFileName('getFileName/index.js') // => index.js */ export default function getFileName(path) { return path.replace(/^.*[\\\/]/, ''); } 

if you use nodejs, you can install a package that includes this feature https://www.npmjs.com/package/jotils

0
Jan 27 '19 at 15:32
source share



All Articles