除了process.cwd()之外,是否有其他方法来获取当前项目根目录的路径名。Node是否实现了ruby的属性Rails.root之类的东西。我要找的是稳定可靠的东西。


当前回答

1-在项目根目录下创建一个名为settings.js的文件

2-在此文件中添加此代码

module.exports = {
    POST_MAX_SIZE : 40 , //MB
    UPLOAD_MAX_FILE_SIZE: 40, //MB
    PROJECT_DIR : __dirname
};

3-在node_modules中创建一个名为“settings”的新模块,并在index.js模块中编写以下代码:

module.exports = require("../../settings");

4-任何时候你想要你的项目目录只需使用

var settings = require("settings");
settings.PROJECT_DIR; 

通过这种方式,您将拥有与此文件相关的所有项目目录;)

其他回答

const __root = `${__dirname.substring(0, __dirname.lastIndexOf('projectName'))}projectName`

`

这将沿着目录树向下走,直到它包含一个node_modules目录,通常表示你的项目根目录:

const fs = require('fs')
const path = require('path')

function getProjectRoot(currentDir = __dirname.split(path.sep)) {
  if (!currentDir.length) {
    throw Error('Could not find project root.')
  }
  const nodeModulesPath = currentDir.concat(['node_modules']).join(path.sep)
  if (fs.existsSync(nodeModulesPath) && !currentDir.includes('node_modules')) {
    return currentDir.join(path.sep)
  }
  return this.getProjectRoot(currentDir.slice(0, -1))
}

它还确保返回路径中没有node_modules,因为这意味着它包含在嵌套包安装中。

的过程。mainModule自v 14.0.0起已弃用。参考答案时,请使用require。主要部分,其余部分还在。

process.mainModule.paths
  .filter(p => !p.includes('node_modules'))
  .shift()

获取主模块中的所有路径,并过滤掉带有"node_modules"的路径, 然后获取剩余路径列表中的第一个。意外行为不会抛出错误,只是一个未定义的错误。

对我来说很好,即使在调用ie $ mocha时也是如此。

在npm的现代版本中,你可以在exports中添加一个条目,用作速记。注意,如果你想同时引用根目录本身和根目录下的文件,你需要分别使用./和./*:

package.json:

{
  "imports": {
    "#root": "./",
    "#root/*": "./*",
    ...
  },
  ...
}

/ index.js:

import {namedExport} from '#root/file.js'

/ file.js:

export const namedExport = {
  hi: "world",
};

然后:

$ node --experimental-specifier-resolution=node index.js

你可以用constants.js文件进一步扩展它,在那里你可以使用上面答案中的一个方法,或者输入一个绝对路径,如果你需要路径本身的话

尝试从__dirname向上遍历,直到找到一个包。Json,并确定这是你当前文件所属的应用主根目录。

根据Node文档

包。json文件通常位于Node.js项目的根目录。

const fs = require('fs')
const path = require('path')

function getAppRootDir () {
  let currentDir = __dirname
  while(!fs.existsSync(path.join(currentDir, 'package.json'))) {
    currentDir = path.join(currentDir, '..')
  }
  return currentDir
}