简体   繁体   English

如何在NodeJs中创建消耗文件相对路径的功能(内部模块)

[英]How to create function (inside module) that consume relative path of file in NodeJs

What I am trying to do is creating function like NodeJS require . 我正在尝试创建像NodeJS require这样的函数。 You can do require("./your-file") and require understand that the file ./your-file is sibling of the calling module, without specifying the full path of the file. 您可以执行require("./your-file")require了解文件./your-file是调用模块的同级文件,而无需指定文件的完整路径。

My current problem is getting the directory of current executing function ( __dirname of the executing function) 我当前的问题是获取当前执行函数的目录(执行函数的__dirname

I tried things below: 我尝试了以下内容:

  • Using module.parent.fileName failed when the calling method wrapped with other function. 当调用方法与其他函数包装在一起时,使用module.parent.fileName失败。
  • By reading from V8 stack trace almost there but failed when run inside test runner (Jest) 通过从V8堆栈跟踪中读取几乎所有内容,但是在测试运行程序(Jest)中运行时失败

It should be an easy solution for this, maybe I'm over complicate it? 这应该是一个简单的解决方案,也许我太复杂了?

May be you should use: 可能是您应该使用:

var path = require('path'); 
//_dirname will give you the current position

using path package you can achieve this. 使用路径包可以实现这一点。 find Documentation here 在这里找到文档

Both module.parent.fileName and V8 stack trace works fine , but it will failed if you export the module in the index.js module.parent.fileName和V8堆栈跟踪都可以正常工作 ,但是如果在index.js导出模块,它将失败。

example: 例:

//src/my-lib.js

function myFunction(){
   const path = module.parent.fileName
   //do stuff
}

then you export the function above in the index.js 然后在index.js导出上面的函数

//src/index.js
const lib = require("./my-lib")

exports.myFunction = lib.myFunction

in the client code if you import myFunction from index.js the path detected will always /src/index.js 在客户端代码中,如果您从index.js导入myFunction ,则检测到的path将始终为/src/index.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM