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


当前回答

__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}`);

其他回答

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

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

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

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

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

一个非常简单和可靠的解决办法是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
}
const __root = `${__dirname.substring(0, __dirname.lastIndexOf('projectName'))}projectName`

`

只使用:

 path.resolve("./") ... output is your project root directory

我用这个。

我的模块名为mymodule

var BASE_DIR = __dirname.replace(/^(.*\/mymodule)(.*)$/, '$1')