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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…