我想知道如何获得函数调用者的绝对路径?
让我们说:
在文件中a.js我打电话b(); b()是文件中定义的函数b.js.a.js需要b.那么如何a.js从b.js节点中获取绝对路径?
所以我有可用于国际化的节点模块.
我正在尝试获取在结节模块中运行我的节点模块的文件的当前路径.
用例#1:
内 ~/yourProject/node_modules/i18n.js
var current_path_to_locales_dir = path.join(__dirname, "locale");
Run Code Online (Sandbox Code Playgroud)
而服务器的路径是:
~/YourUserName/yourProject/app.js
Run Code Online (Sandbox Code Playgroud)
干 var i18n = require("i18n");
并试图获得它将返回的路径
/User/YourUserName/yourProject/node_modules/locale
Run Code Online (Sandbox Code Playgroud)
这是正确的,但我期待它寻找
/User/YourUserName/yourProject/locale
Run Code Online (Sandbox Code Playgroud)
用例#2:
内 ~/i18nProject/i18n.js
var current_path_to_locales_dir = path.join(__dirname, "locale");
Run Code Online (Sandbox Code Playgroud)
如果我有一个示例应用程序在~/i18nProject/sample做和var i18n = require("../i18n");
这次locale目录将是
/User/YourUserName/i18nProject/locale
Run Code Online (Sandbox Code Playgroud)
以上是正确的,但我希望它是正确的
/User/i18nProject/sample/locale/
Run Code Online (Sandbox Code Playgroud)
现在我想知道是否有办法让我可以获得当前运行脚本的路径?
我正在编写一个反应库(react-xarrows.tsx),当用户向我的组件提供错误的属性时,会抛出错误(我写的),但它显示了我在“react-arrows.tsx”中编写的行。
出错时用户将看到:
/src/Xarrow.tsx:184:12
if (!("current" in props.start))
throw Error(
`'start' property is not of type reference.
maybe you set 'start' to other object and not to React reference?.\n`
);
Run Code Online (Sandbox Code Playgroud)
我想准确地向用户指出他出错的地方 - 我可以通过向 Error 提供“文件名”来做到这一点 - Error([message[, fileName[, lineNumber]]]) - 导入文件的文件名当前模块,使用我的库的用户文件 - 让我们将该文件称为“/src/Example5.tsx”。(关于“名称”我当然是指相对路径)
现在,我需要弄清楚如何获取该文件名(以及稍后的行号)。
(我确实尝试从“moudle.parents”对象中获取它作为其他类似问题的答案,但没有任何模块对象的父属性。 这是最接近帮助我的。)
必须有一种方法可以做到这一点,因为反应本身会向用户指出他出错的地方。我现在在Example5 中留下了一个错误示例(只需单击Example5)。您可以自由地使用它,如果您想出解决方案,请分享。
简化示例5:
/src/Xarrow.tsx:184:12
if (!("current" in props.start))
throw Error(
`'start' property is not of type reference.
maybe you set 'start' to other object and not to React reference?.\n`
);
Run Code Online (Sandbox Code Playgroud) 我想在父类中创建一个方法,该方法将返回扩展它的每个子类的位置.
// Class A dir is '/classes/a/
class A{
getPath(){
console.log(__dirname);
return (__dirname);
}
}
// Class B dir is '/classes/b'
class B extends A{
}
new A().getPath(); // Prints '/classes/a'
new B().getPath(); // Prints '/classes/a' (I want here '/classes/b');Run Code Online (Sandbox Code Playgroud)
我理解为什么B类打印A的位置,但我正在寻找一个在父类上创建一个方法的选项,它将打印子类的位置.我不想覆盖每个子类中的方法,因为它忽略了这一点
我也试过process.pwd()了.