除了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,因为这意味着它包含在嵌套包安装中。

其他回答

这样做:

path.join(...process.argv[1].split(/\/|\\/).slice(0, -1))

的过程。mainModule自v 14.0.0起已弃用。参考答案时,请使用require。主要部分,其余部分还在。

process.mainModule.paths
  .filter(p => !p.includes('node_modules'))
  .shift()

获取主模块中的所有路径,并过滤掉带有"node_modules"的路径, 然后获取剩余路径列表中的第一个。意外行为不会抛出错误,只是一个未定义的错误。

对我来说很好,即使在调用ie $ mocha时也是如此。

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; 

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

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

我写了一个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' });

在npm的现代版本中,你可以在exports中添加一个条目,用作速记。注意,如果你想同时引用根目录本身和根目录下的文件,你需要分别使用./和./*:

package.json:

{
  "imports": {
    "#root": "./",
    "#root/*": "./*",
    ...
  },
  ...
}

/ index.js:

import {namedExport} from '#root/file.js'

/ file.js:

export const namedExport = {
  hi: "world",
};

然后:

$ node --experimental-specifier-resolution=node index.js

你可以用constants.js文件进一步扩展它,在那里你可以使用上面答案中的一个方法,或者输入一个绝对路径,如果你需要路径本身的话