Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - getting current filename

Tags:

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

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

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

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


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.