Node.js - getting current filename

后端 未结 8 858
执念已碎
执念已碎 2020-12-13 08:04

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

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

相关标签:
8条回答
  • 2020-12-13 08:25

    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

    0 讨论(0)
  • 2020-12-13 08:29

    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.

    0 讨论(0)
  • 2020-12-13 08:36
    '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.

    0 讨论(0)
  • 2020-12-13 08:37

    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);
    
    0 讨论(0)
  • 2020-12-13 08:40

    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);
    
    0 讨论(0)
  • 2020-12-13 08:40

    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));
    
    0 讨论(0)
提交回复
热议问题