简体   繁体   English

如何在节点中导入的js文件中获取当前路径

[英]How do I get the current path in my imported js file in node

I have 2 files A.js and B.js , they are structured as follows: 我有2个文件A.jsB.js ,它们的结构如下:

packgages
|
 – B
   |
    - B.js
A.js

In my A.js I simply do this: 在我的A.js我只是这样做:

import B.js

In my B.js I want to know the full path to this file ( B.js ): 在我的B.js我想知道此文件( B.js )的完整路径:

console.log(__dirname);

So if I execute cd packages/B; node B.js 所以如果我执行cd packages/B; node B.js cd packages/B; node B.js I get the following result: cd packages/B; node B.js我得到以下结果:

/Users/luke/Projekte/writejs/code/verne/packages/B

But if I excecute node A.js I get this: 但是,如果我执行node A.js得到以下信息:

/Users/luke/Projekte/writejs/code/verne

See that the __dirname does not refer to the file from which is it called but to the file that executes it in its root. 可以看到__dirname并不指向被调用的文件,而是指向在其根目录中执行该文件的文件。

Is there a way to get the full path to /packages/B no matter which file I am importing it from? 无论我从哪个文件导入文件,都有办法获取/packages/B的完整路径吗?

I have never worked with Rollup, but from what I can understand from the introduction on its page, its purpose is to transpile ES6 scripts into a single js file. 我从未使用过Rollup,但是从其页面上的介绍中可以理解,其目的是将ES6脚本转换为单个js文件。 So if have the following files: 因此,如果具有以下文件:

moduleA.js moduleA.js

import p from "./myModules/moduleB";

console.log(__dirname);
console.log(__filename);

p();

myModules/moduleB.js myModules / moduleB.js

export default function () {
  console.log(__dirname);
  console.log(__filename);
}

When executing Rollup on moduleA.js 在moduleA.js上执行汇总时

rollup -i moduleA.js -f cjs -o rollup.js 

I obtain the following file: 我获得以下文件:

rollup.js rollup.js

'use strict';

function p () {
  console.log(__dirname);
  console.log(__filename);
}

console.log(__dirname);
console.log(__filename);

p();

As you can see, any reference to the previous structure is gone. 如您所见,对先前结构的任何引用均已消失。 Also, everything is in one single file, so the directory would not change. 而且,所有内容都在一个文件中,因此目录不会更改。

I have also tried to find a way to maintain the directory structure when creating Rollup bundle, but can't find any solution. 我还尝试过在创建Rollup捆绑包时找到一种维护目录结构的方法,但是找不到任何解决方案。

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

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