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


当前回答

这将沿着目录树向下走,直到它包含一个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时也是如此。

所有这些“根dirs”大多需要解析一些虚拟路径到一个真实的堆路径,所以可能你应该看看path.resolve?

var path= require('path');
var filePath = path.resolve('our/virtual/path.ext');

我知道这已经太迟了。 但我们可以通过两个方法获取根URL

1号方法

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

2方法

var path = require('path');
path.dirname(process.mainModule.filename);

参考链接:—https://gist.github.com/geekiam/e2e3e0325abd9023d3a3

你也可以使用 Git rev-parse——show- topllevel 假设您正在使用git存储库

一个非常简单和可靠的解决办法是cd ..递归地搜索包。Json,考虑到这个文件总是在项目根目录。

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
}