【问题标题】:Get path to first called/started module by node command通过节点命令获取第一个调用/启动模块的路径
【发布时间】:2016-09-15 14:33:29
【问题描述】:

如何获取“第一个调用模块”所在目录的路径?

例如,我们在 /bin/ 文件夹中有一个名为 startnode.sh 的 bash 文件

node ~/path/to/file/index.js

现在在 index.js 中,我们有复杂的代码需要其他文件,例如:

var myMoudle = require("./module.js");

等等。现在我们在随机文件夹中:/qpa/dir/ 然后通过 bash 文件启动我们的节点进程:

startnode

在我们的module.js 中,我们将获得工作目录:

console.log(process.cwd());

惊喜! process.cwd() 返回 /qpa/dir/ 而不是 ~/path/to/file/

为什么?

我需要节点进程开始的目录,第一个调用模块的目录。

【问题讨论】:

  • 对不起,我第一次阅读时没有正确理解您需要什么。

标签: node.js path


【解决方案1】:

使用环境变量:

考虑以下结构:

test
├── bin.sh
└── test
    └── hello.js

在 bin.sh 中:

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" node BASE_PATH/test/test/hello.js

在 hello.js 中:

console.log(__dirname); // BASE_PATH/test/test
console.log(process.env.DIR); // BASE_PATH/test
console.log(process.cwd()); // BASE_PATH

注意:您需要将 BASE_PATH 替换为您的路径 (~/path/to/file/)

【讨论】:

    猜你喜欢
    • 2017-07-04
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 2015-11-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-20
    相关资源
    最近更新 更多