Raxit Sheth
Raxit Sheth

Reputation: 2591

Node.js - getting current filename

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

Upvotes: 182

Views: 155118

Answers (10)

CrazyTim
CrazyTim

Reputation: 7316

If you are using ES modules do this:

import path from 'node:path';
const FILE_URL = import.meta.url;
const FILE_NAME = path.basename(import.meta.url);
const FILE_NAME_WITHOUT_EXT = path.basename(import.meta.url, path.extname(import.meta.url));

console.log({
  FILE_URL,
  FILE_NAME,
  FILE_NAME_WITHOUT_EXT
});

Note: __dirname and __filename are not available in Node for ES modules.

Upvotes: 4

Roi
Roi

Reputation: 1647

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.

Upvotes: 1

Josh
Josh

Reputation: 668

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

Upvotes: 1

Marcus
Marcus

Reputation: 57

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.

Upvotes: 1

ilyaigpetrov
ilyaigpetrov

Reputation: 3883

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

Upvotes: 27

TacB0sS
TacB0sS

Reputation: 10266

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("."))

Upvotes: 1

Red Walrus
Red Walrus

Reputation: 567

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));

Upvotes: 55

herve
herve

Reputation: 3954

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);

Upvotes: 315

Anthony McCormick
Anthony McCormick

Reputation: 2744

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);

Upvotes: 58

heinob
heinob

Reputation: 19464

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.

Upvotes: 3

Related Questions