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


当前回答

我用这个。

我的模块名为mymodule

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

其他回答

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

你也可以使用 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' });

__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.resolve("./") ... output is your project root directory