Node.js - getting current filename

node.js

node.js Problem Overview


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

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

node.js Solutions


Solution 1 - node.js

Node.js provides a standard API to do so: Path.

Getting the name of the current script is then easy:

var path = require('path');
var scriptName = path.basename(__filename);

Solution 2 - node.js

within a module you can do any of the following to get the full path with filename

this.filename;
module.filename;
__filename;

If you just want the actual name with no path or extension you can do something like this.

module.filename.slice(__filename.lastIndexOf(path.sep)+1, module.filename.length -3);

Solution 3 - node.js

To get the file name only. No additional module simply:

// abc.js
console.log(__filename.slice(__dirname.length + 1));

 // abc
console.log(__filename.slice(__dirname.length + 1, -3));

Solution 4 - node.js

'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 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'

Don't Use This

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.

Solution 5 - node.js

You might also look at console-plus. This adds filename and linenumber to any logging text and has different colours for .log, .info and .error.

Solution 6 - node.js

Well, I wanted to use the file name as the tag for the logger so the most straight forward and what I wanted is this:

__filename.substring(__dirname.length + 1, __filename.lastIndexOf("."))

Solution 7 - node.js

I know it's been already a long time, but what I did is __filename.split('\\').pop(). This will get the full path with the filename, split it by \ then get the last index which will be your filename.

Solution 8 - node.js

you can use this function to get filename:

/**
 * @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 the package that include this function https://www.npmjs.com/package/jotils

Solution 9 - node.js

Only because I don't see it listed here, another option is to just remove the __dirname from the __filename.

__filename.replace(`${__dirname}/`, '')

I think that is useful if you don't want to import a the path module. However, I do believe that path.basename(__filename) is the most appropriate.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRaxit ShethView Question on Stackoverflow
Solution 1 - node.jsherveView Answer on Stackoverflow
Solution 2 - node.jsAnthony McCormickView Answer on Stackoverflow
Solution 3 - node.jsRed WalrusView Answer on Stackoverflow
Solution 4 - node.jsilyaigpetrovView Answer on Stackoverflow
Solution 5 - node.jsheinobView Answer on Stackoverflow
Solution 6 - node.jsTacB0sSView Answer on Stackoverflow
Solution 7 - node.jsMarcusView Answer on Stackoverflow
Solution 8 - node.jsJoshView Answer on Stackoverflow
Solution 9 - node.jsRoiView Answer on Stackoverflow