【问题标题】:The process.env not defined after deploying to ubuntu 18.04部署到 ubuntu 18.04 后未定义 process.env
【发布时间】:2020-02-04 07:21:39
【问题描述】:

我从我的 win10 PC 开发中将我的 nodejs 10.16.3 应用程序部署到 ubuntu 18.04。问题是 process.env 在 ubuntu 服务器上变为 undefineddotenv 模块用作:

require('dotenv').config({path: process.cwd() +'/config/.env'});

服务器正在监听:

const port = process.env.PORT; // 3000;
console.log(process.env);

server.listen(port, () => {
  console.log(`env var: ${process.env.jwtPrivateKey}`)
  console.log(`Listening on port ${port}...`);

});

myproj\config\ 下有一个.env 文件存储所有用户定义的参数。她是文件的一部分:

PORT = 3000
DB_PASSWORD = mydbpassword
jwtPrivateKey = myprivatekey
jwt_token_expire_days = 24
jwt_secret_len = 10
vcode_time_elapse = 10

使用以下命令启动 nodejs 应用程序后:

pm2 start /ebs/www/myapp/index.js

这是来自index-out.log的打印输出:

$cat index-out.log
env var: undefined
Listening on port undefined...

这里是index-error.log

$ cat index-error.log
Unable to connect to the database: { SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:5433
    at connection.connect.err (/ebs/www/emps/node_modules/sequelize/lib/dialects/postgres/connection-manager.js:170:24)
    at Connection.connectingErrorHandler (/ebs/www/emps/node_modules/pg/lib/client.js:174:14)
    at Connection.emit (events.js:198:13)
    at Socket.reportStreamError (/ebs/www/emps/node_modules/pg/lib/connection.js:72:10)
    at Socket.emit (events.js:198:13)
    at emitErrorNT (internal/streams/destroy.js:91:8)
    at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
    at process._tickCallback (internal/process/next_tick.js:63:19)
  name: 'SequelizeConnectionRefusedError',
  parent:
   { Error: connect ECONNREFUSED 127.0.0.1:5433
       at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1106:14)
     errno: 'ECONNREFUSED',
     code: 'ECONNREFUSED',
     syscall: 'connect',
     address: '127.0.0.1',
     port: 5433 },
  original:
   { Error: connect ECONNREFUSED 127.0.0.1:5433
       at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1106:14)
     errno: 'ECONNREFUSED',
     code: 'ECONNREFUSED',
     syscall: 'connect',
     address: '127.0.0.1',
     port: 5433 } }

它必须与dotenv 模块的配置有关。

【问题讨论】:

  • dotenv 如果无法在您声明的路径中找到文件,则会返回错误。还有一个调试选项,在这种情况下也很有帮助。

标签: node.js ubuntu dotenv


【解决方案1】:

更改您的 require dotenv 语句
require('dotenv').config({path: process.cwd() +'/config/.env'});

require('dotenv').config({path: __dirname +'/config/.env'});

由于项目是使用以下命令从不同位置启动的,因此无法读取 .env 文件:

pm2 start /ebs/www/myapp/index.js

process.cwd() 和 __dirname 的区别:

process.cwd() 返回当前工作目录,即您从中调用node 命令的目录。

__dirname 返回包含 JavaScript 源代码文件的目录的目录名

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 2015-05-19
    • 2022-01-04
    • 2021-11-23
    • 2019-08-12
    • 1970-01-01
    • 2019-10-15
    相关资源
    最近更新 更多