Node.js - getting current filename

后端 未结 8 857
执念已碎
执念已碎 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: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.

提交回复
热议问题