本文翻译自:Determine project root from a running node.js application
Is there a better way than process.cwd()
to determine the root directory of a running node.js process? 有没有比process.cwd()
更好的方法来确定正在运行的node.js进程的根目录? Something like the equivalent of Rails.root
, but for Node.js. 类似于Rails.root
,但适用于Node.js。 I'm looking for something that is as predictable and reliable as possible. 我正在寻找尽可能可预测和可靠的东西。
#1楼
参考:https://stackoom.com/question/H4Bo/从运行的node-js应用程序确定项目根目录
#2楼
__dirname
isn't a global; __dirname
不是全局的; it's local to the current module so each file has its own local, different value. 它在当前模块本地,因此每个文件都有其自己的本地值。
If you want the root directory of the running process, you probably do want to use process.cwd()
. 如果要运行的进程的根目录,则可能确实要使用process.cwd()
。
If you want predictability and reliability, then you probably need to make it a requirement of your application that a certain environment variable is set. 如果需要可预测性和可靠性,则可能需要使您的应用程序要求设置某个环境变量。 Your app looks for MY_APP_HOME
(Or whatever) and if it's there, and the application exists in that directory then all is well. 您的应用程序查找MY_APP_HOME
(或其他),如果存在,并且该应用程序存在于该目录中,则一切正常。 If it is undefined or the directory doesn't contain your application then it should exit with an error prompting the user to create the variable. 如果未定义或目录不包含您的应用程序,则它应退出并出现错误提示用户创建变量。 It could be set as a part of an install process. 可以将其设置为安装过程的一部分。
You can read environment variables in node with something like process.env.MY_ENV_VARIABLE
. 您可以使用诸如process.env.MY_ENV_VARIABLE
类的内容读取节点中的环境变量。
#3楼
1- create a file in the project root call it settings.js 1-在项目根目录中创建一个文件,将其称为settings.js
2- inside this file add this code 2-在此文件中添加此代码
module.exports = {
POST_MAX_SIZE : 40 , //MB
UPLOAD_MAX_FILE_SIZE: 40, //MB
PROJECT_DIR : __dirname
};
3- inside node_modules create a new module name it "