简体   繁体   English

在 javascript 中处理跨模块的相对路径

[英]Handling relative paths across modules in javascript

So let's say I have a.js file which exposes a function, which I want to be able to import in many other files.因此,假设我有一个 .js 文件,它公开了一个 function,我希望能够将其导入到许多其他文件中。 The function in this file needs access to some data stored in a certain file ( take.txt for this example) and I'm using the relative address to read and write to this text file.此文件中的 function 需要访问存储在某个文件中的某些数据(本示例为 take.txt),我使用相对地址来读取和写入此文本文件。

Now the problem comes when I import this module into other files in different directories, the relative paths won't be valid but I don't know how I can change this?现在问题来了,当我将此模块导入不同目录中的其他文件时,相对路径将无效但我不知道如何更改它? I'm sure there's a simple way to do this but I can't figure it out at all.我确信有一种简单的方法可以做到这一点,但我根本无法弄清楚。

file 1文件 1

relative path = '../../file.txt'
function foo(){
  fs.readFile(relativePath)
}
module.exports = {foo}

file 2文件 2

const {foo} = require('foo')
foo();

It doesn't actually matter which other modules load this module.实际上,哪些其他模块加载此模块并不重要。 The path is going to be resolved relative to the current working directory , which depends on in which directory your shell is in when you invoke the code.该路径将相对于当前工作目录进行解析,这取决于您调用代码时 shell 所在的目录。

If you want it to resolve relative to that specific JavaScript file, then you can use __dirname :如果您希望它相对于该特定 JavaScript 文件进行解析,则可以使用__dirname

const path = require('path');
// ...
fs.readFile(path.join(__dirname, relativePath));

you can use resolve method of path package like您可以使用路径 package 的解析方法,例如

const path = require('path').resolve
path.resolve('../../file.txt')

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

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