繁体   English   中英

如何在 node.js 中获取导入文件的相对路径

[英]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();

我有哪些选择? 甚至可能吗?

您可以获得导入文件的相对路径,如下所示

第一种方法:(修改导入的文件):

  1. 假设您有一个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
  1. 现在在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.jstest/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.

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