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


当前回答

你可以简单地在express app变量中添加根目录路径,并从app中获取这个路径。在index.js或app.js文件中。并使用req.app.get('rootDirectory')在代码中获取根目录路径。

其他回答

获得全局根的最简单方法(假设你使用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'),它非常适合这个目的

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

找到电子应用程序的根路径可能会很棘手。因为在不同的条件下,例如生产、开发和打包条件下,主进程和渲染器的根路径是不同的。

我写了一个npm包electronic -root-path来捕获电子应用程序的根路径。

$ npm install electron-root-path

or 

$ yarn add electron-root-path


// Import ES6 way
import { rootPath } from 'electron-root-path';

// Import ES2015 way
const rootPath = require('electron-root-path').rootPath;

// e.g:
// read a file in the root
const location = path.join(rootPath, 'package.json');
const pkgInfo = fs.readFileSync(location, { encoding: 'utf8' });

就像在根目录中添加这一行到你的模块一样简单,通常是app.js或app.ts。

global.__basedir = __dirname;

然后所有模块都可以访问_basedir。

注意:对于typescript实现,遵循上面的步骤,然后你将能够使用global.__basedir使用根目录路径

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