javascript 如何在方法 node.js 中获取方法名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16712847/
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
How to get a method name inside a method node.js
提问by Amol M Kulkarni
Scenario: Consider I am having multiple methods doing different tasks and handled by different developers. I am trying to make a generic method call which logs if error occurs. So the need is I have to log a Line No, Method name, etc..
场景:考虑到我有多种方法执行不同的任务并由不同的开发人员处理。我正在尝试进行通用方法调用,如果发生错误,该调用会记录下来。所以需要的是我必须记录行号、方法名称等。
I wrote a generic function, as follows:
我写了一个泛型函数,如下:
function enterLog(sourcefile, methodName, LineNo)
{
fs.appendFile('errlog.txt', sourcefile +'\t'+ methodName +'\t'+ LineNo +'\n', function(e){
if(e)
console.log('Error Logger Failed in Appending File! ' + e);
});
}
So, the call for the above method has to pass source file, method name and the Line No. Which may change at any point of time during development.
因此,对上述方法的调用必须传递源文件、方法名称和行号。这些在开发过程中可能随时更改。
E.g. for calling method with hard-coded values:
例如,使用硬编码值调用方法:
enterLog('hardcodedFileName.js', 'TestMethod()', '27');
Question: Is it better to hard-code the values (as above example) required or is there any way to get the method name & line no reference from any way in Node.js?
问题:是否更好地对所需的值(如上例)进行硬编码,或者有什么方法可以在 Node.js 中以任何方式获取方法名称和行无引用?
采纳答案by hereandnow78
there is a nice module out there which we use in our applications-logger. you can even fetch the line number. https://npmjs.org/package/traceback
我们在应用程序记录器中使用了一个很好的模块。你甚至可以获取行号。https://npmjs.org/package/traceback
so you could rewrite it like that:
所以你可以像这样重写它:
var traceback = require('traceback');
function enterLog(sourcefile, methodName, LineNo) {
var tb = traceback()[1]; // 1 because 0 should be your enterLog-Function itself
fs.appendFile('errlog.txt', tb.file +'\t'+ tb.method +'\t'+ tb.line +'\n', function(e) {
if(e) {
console.log('Error Logger Failed in Appending File! ' + e);
}
});
}
and just call:
只需调用:
enterLog();
from wherever you want and always get the correct results
从您想要的任何地方,并始终获得正确的结果
Edit: another hint. not hardcoding your filename is the easiest to achieve in node.js without 3rd-party-module-dependencies:
编辑:另一个提示。在没有 3rd-party-module-dependencies 的 node.js 中,不硬编码你的文件名是最容易实现的:
var path = require('path');
var currentFile = path.basename(__filename); // where __filename always has the absolute path of the current file
回答by Thomas Junk
You may have a look at
你可以看看
https://developer.mozilla.org/de/docs/JavaScript/Reference/Global_Objects/Function/caller
https://developer.mozilla.org/de/docs/JavaScript/Reference/Global_Objects/Function/caller
one property is "name".
一个属性是“名称”。