除了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; 

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

其他回答

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

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

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

获得全局根的最简单方法(假设你使用NPM来运行你的node.js应用程序' NPM start',等等)

var appRoot = process.env.PWD;

如果你想交叉验证上面的内容

假设你想交叉检查process.env.PWD与node.js应用程序的设置。如果您想要一些运行时测试来检查process.env的有效性。PWD,你可以用这段代码(我写的似乎工作得很好)交叉检查它。你可以用包中的npm_package_name交叉检查apot中最后一个文件夹的名称。Json文件,例如:

    var path = require('path');

    var globalRoot = __dirname; //(you may have to do some substring processing if the first script you run is not in the project root, since __dirname refers to the directory that the file is in for which __dirname is called in.)

    //compare the last directory in the globalRoot path to the name of the project in your package.json file
    var folders = globalRoot.split(path.sep);
    var packageName = folders[folders.length-1];
    var pwd = process.env.PWD;
    var npmPackageName = process.env.npm_package_name;
    if(packageName !== npmPackageName){
        throw new Error('Failed check for runtime string equality between globalRoot-bottommost directory and npm_package_name.');
    }
    if(globalRoot !== pwd){
        throw new Error('Failed check for runtime string equality between globalRoot and process.env.PWD.');
    }

你也可以使用这个NPM模块:require('app-root-path'),它非常适合这个目的

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

尝试path._makeLong(“some_filename_on_root.js”);

例子:

cons path = require('path');
console.log(path._makeLong('some_filename_on_root.js');

这将返回你的节点应用程序的根目录的完整路径(与package.json相同的位置)