代码之家  ›  专栏  ›  技术社区  ›  user938363

部署到Ubuntu18.04后未定义process.env

  •  0
  • user938363  · 技术社区  · 5 年前

    process.env 变成 undefined 在ubuntu服务器上。这个 dotenv

    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}...`);
    
    });
    

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

    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 } }
    

    模块。

    0 回复  |  直到 5 年前
        1
  •  2
  •   Sanket Phansekar    5 年前

    将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()和\uu dirname之间的区别:

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

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

    推荐文章