[英]How to get relative path to an imported file in node.js
我有以下文件:
import {something} from '../../something';
something.do();
而且我想将something
的相对路径作为字符串获取,但要动态地而不是隐式地编写它。 像这样的东西:
import {something} from '../../something';
getPath(something); // will return '../../something'
something.do();
我有哪些选择? 甚至可能吗?
您可以获得导入文件的相对路径,如下所示
第一种方法:(修改导入的文件):
test
文件夹。 在test
文件夹中,您有test1.js
和/mod/test2.js
文件。测试/mod/test2.js
// here are some of your codes
export const importedFilePath = import.meta.url; // export current file absoulte path
test/test1.js
文件中:path.relative(from, to) 方法根据当前工作目录返回相对路径 from to to。 如果 from 和 to 每个解析到相同的路径(在每个上调用 path.resolve() 之后),则返回零长度字符串。
如果零长度字符串作为 from 或 to 传递,则将使用当前工作目录而不是零长度字符串。 文档
import path from 'path'
import { importedFilePath } from './mod/test2.js';
const currentFilePath = import.meta.url;
console.log(path.relative(currentFilePath, importedFilePath));
输出:
..\mod\test2.js
现在你有了from test/test1.js
到test/mod/test2.js
的相对路径
我知道这不是一个完美的解决方案,但您可以使用上述方法获得您想要的结果。
第二种方法
如果您将使用 CommonJS 模块系统,您可以在不修改导入文件的情况下实现此结果。
假设您使用 CommonJS 模块。 无需对导入的文件进行任何修改即可达到与上述相同的结果,如下所示:
test/test1.js
文件:
const file = require('./mod/test2');
const path = require('path');
const importedFilePath=require.cache[__filename].children[0].id; //this returns imported file path
const currentFilePath = __filename;
console.log(path.relative(currentFilePath, importedFilePath));
并输出:
..\mod\test2.js
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.