Node.js - 获取当前文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14201475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:53:39  来源:igfitidea点击:

Node.js - getting current filename

node.js

提问by Raxit Sheth

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

我想将它用于日志记录/调试目的,相当于__FILE__, __LINE__in c

回答by herve

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

Node.js 为此提供了一个标准 API:Path

Getting the name of the current script is then easy:

获取当前脚本的名称很容易:

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

回答by Anthony McCormick

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

回答by Red Walrus

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

回答by ilyaigpetrov

'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 splitfunction with regular expressionas 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 /[\\/]/.

这里我们使用带有正则表达式的split函数作为第一个参数。 我们想要的分隔符的正则表达式是(split by or ) 但必须对符号进行转义以将其与正则表达式终止符区分开来,因此.
[\/]/\///[\\/]/

const scriptName = __filename.split(/[\/]/).pop(); // Remove the last array element
console.log(scriptName);
// 'yourScript.js'

Don't Use This

不要使用这个

You really should use path.basenameinstead (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 pathanswer above.

你真的应该path.basename改用(首先记录在 Node.js v0.1.25 中),因为它处理所有你不想知道的极端情况,比如里面有斜杠的文件名(例如在 unix 上名为“foo\bar”的文件)。请参阅上面的path答案。

回答by heinob

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.

您也可以查看console-plus。这会将文件名和行号添加到任何日志记录文本中,并且 .log、.info 和 .error 具有不同的颜色。

回答by TacB0sS

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

回答by Marcus

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.

我知道这已经很长时间了,但我所做的是__filename.split('\\').pop()。这将获得文件名的完整路径,\然后将其拆分,然后获得最后一个索引,这将是您的文件名。

回答by Josh

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

如果你使用 nodejs,你可以安装包含这个功能的包 https://www.npmjs.com/package/jotils