除了process.cwd()之外,是否有其他方法来获取当前项目根目录的路径名。Node是否实现了ruby的属性Rails.root之类的东西。我要找的是稳定可靠的东西。
当前回答
一个非常简单和可靠的解决办法是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
}
其他回答
__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}`);
获得全局根的最简单方法(假设你使用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'),它非常适合这个目的
在使用express时,我发现一个有用的技巧是在设置任何其他路由之前将以下内容添加到app.js中
// set rootPath
app.use(function(req, res, next) {
req.rootPath = __dirname;
next();
});
app.use('/myroute', myRoute);
不需要使用全局变量,您可以将根目录的路径作为请求对象的属性。
如果你的app.js在你的项目的根目录中,这是有效的,默认情况下,它是。
你也可以使用 Git rev-parse——show- topllevel 假设您正在使用git存储库
在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文件进一步扩展它,在那里你可以使用上面答案中的一个方法,或者输入一个绝对路径,如果你需要路径本身的话
推荐文章
- ReferenceError: description没有定义NodeJs
- 将一个二进制的NodeJS Buffer转换为JavaScript的ArrayBuffer
- AngularJS只适用于单页应用程序吗?
- 如何在vue-cli项目中更改端口号
- 同步和异步编程(在node.js中)的区别是什么?
- 如何编辑通过npm安装的节点模块?
- “node_modules”文件夹应该包含在git存储库中吗
- 使用package.json在全局和本地安装依赖项
- this.libOptions.parse不是一个函数
- 对嵌套文件夹运行npm install的最好方法是什么?
- 节点Multer异常字段
- 很好的初学者教程socket.io?
- CALL_AND_RETRY_LAST分配失败-进程内存不足
- 在Ubuntu上安装Node.js
- 使用express.js代理