Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

javascript - 获取主模块的__dirname(Get __dirname of main module)

I'm writting a NPM package and I need to know, within this package, what is the __dirname value of the main module.

(我正在编写一个NPM程序包,我需要在该程序包中知道主模块的__dirname值是__dirname 。)

By "main module", I mean the module that isn't a dependency.

(“主模块”是指不是依赖性的模块。)

example:

(例:)

a-project
├─ index.js <--- main module
├─ node_modules
│  ├─ my-package <--- can be a symlink
┊  ┊  └─ index.js <--- I'm here

I tried 2 things:

(我尝试了两件事:)

try 1 (using the current __dirname ):

(尝试1(使用当前的__dirname ):)

const path = require('path');
console.log(`${__dirname}${path.sep}..${path.sep}..`);

-> doesn't work if the package isn't in node_modules but symlinked in node_modules (some packages manager like pnpm do this)

(->如果该软件包不在node_modules而是在node_modules中进行node_modules链接则node_modules (某些软件包管理器(例如pnpm会这样做))

try 2 (using process.argv[1] ):

(尝试2(使用process.argv[1] ):)

 const escapeStringRegexp = require('escape-string-regexp'); const path = require('path'); const escapedPathSep = escapeStringRegexp(path.sep); console.log(process.argv[1].match(new RegExp(`^(.*)${escapedPathSep}.*$`))[1]); 

const path = require('path');
console.log(path.dirname(process.argv[1])

-> doesn't work in production when the main module is lauched by pm2 because process.argv[1] become the location of pm2

(->当主模块被pm2启动时,在生产中不起作用,因为process.argv[1]成为pm2的位置)

I though to use callsite but I think that it will not work if the package isn't a direct dependency of the main module.

(我虽然使用了callsite,但我认为如果程序包不是主要模块的直接依赖项,它将无法正常工作。)

  ask by Cl00e9ment translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The __dirname of main module can be found as follow:

(主模块的__dirname可以找到如下:)

require('path').dirname(require.main.filename);

Since Yury Tarabanko posted a comment and not an answer, I post his response here so I can mark the question as resolved.

(由于Yury Tarabanko发表了评论而非回答,所以我在这里发表他的回答,以便将问题标记为已解决。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...