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


当前回答

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

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

其他回答

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

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

在使用express时,我发现一个有用的技巧是在设置任何其他路由之前将以下内容添加到app.js中

// set rootPath
app.use(function(req, res, next) {
  req.rootPath = __dirname;
  next();
});

app.use('/myroute', myRoute);

不需要使用全局变量,您可以将根目录的路径作为请求对象的属性。

如果你的app.js在你的项目的根目录中,这是有效的,默认情况下,它是。

__dirname会给你根目录,只要你在根目录下的文件中。

// ProjectDirectory.js (this file is in the project's root directory because you are putting it there).
module.exports = {

    root() {
        return __dirname;
    }
}

在其他文件中:

const ProjectDirectory = require('path/to/ProjectDirectory');
console.log(`Project root directory is ${ProjectDirectory.root}`);

一个非常简单和可靠的解决办法是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
}

这将沿着目录树向下走,直到它包含一个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,因为这意味着它包含在嵌套包安装中。