How to get current file name, function name and line number?
I want to use it for logging/debugging purpose, equivalent to __FILE__
, __LINE__
'use strict';
const scriptName = __filename.split(/[\\/]/).pop();
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 split function with regular expression as the first parameter.
The regular expression we want for separator is [\/]
(split by /
or \
) but /
symbol must be escaped to distinguish it from regex terminator /
, so /[\\/]/
.
const scriptName = __filename.split(/[\\/]/).pop(); // Remove the last array element
console.log(scriptName);
// 'yourScript.js'
You really should use path.basename
instead (first documented in Node.js v0.1.25), because it handles all the corner cases you don't want to know about like filenames with slashes inside (e.g. file named "foo\bar" on unix). See path
answer above.