You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Knexfile执行命令行迁移时无法读取.env环境变量

Knex迁移MySQL时权限错误与环境变量读取失败的解决方案

问题描述

执行迁移命令 npx knex migrate:latest 时触发权限错误:

Access denied for user ''@'localhost' (using password: NO)

打印process.env中数据库相关变量均为undefined,但将数据库参数硬编码到knexfile.js后,迁移可正常运行。项目根目录下同时存在knexfile.js和.env文件,knexfile配置代码如下:

require("dotenv").config();
const path = require("path");

const {
  DB_HOST: host,
  DB_NAME: database,
  DB_USER: user,
  DB_PASSWORD: password,
  TEST_DB_NAME: testDatabase,
} = process.env;

/**
 * @type { Object.<string, import("knex").Knex.Config> }
 */
module.exports = {
  development: {
    client: "mysql2",
    connection: {
      host,
      database,
      user,
      password,
      charset: "utf8",
    },
    migrations: {
      directory: path.join(__dirname, "/db/migrations"),
    },
    seeds: {
      directory: path.join(__dirname, "/db/seeds"),
    },
  },
  test: {
    client: "mysql2",
    connection: {
      host,
      database: testDatabase,
      user,
      password,
      charset: "utf8",
    },
    migrations: {
      directory: path.join(__dirname, "/db/migrations"),
    },
    seeds: {
      directory: path.join(__dirname, "/db/seeds"),
    },
  },
};

解决步骤

1. 校验.env文件格式

.env文件必须采用无引号的键值对格式,示例:

DB_HOST=localhost
DB_NAME=your_dev_database
DB_USER=root
DB_PASSWORD=your_db_password
TEST_DB_NAME=your_test_database
  • 禁止给变量值添加单/双引号,否则会被识别为值的一部分
  • 确认文件名是.env,而非.env.txt或其他错误命名

2. 手动指定.env文件路径

默认的dotenv.config()可能无法定位到根目录的.env文件,修改knexfile.js开头代码,明确指定路径:

const path = require("path");
// 先加载path模块,再指定.env路径
require("dotenv").config({ path: path.join(__dirname, ".env") });

const {
  DB_HOST: host,
  DB_NAME: database,
  DB_USER: user,
  DB_PASSWORD: password,
  TEST_DB_NAME: testDatabase,
} = process.env;

3. 确认dotenv依赖已安装

如果未安装dotenv,require("dotenv")不会报错,但无法加载环境变量,执行以下命令安装:

npm install dotenv --save-dev

4. 验证环境变量加载状态

在knexfile.js中添加打印语句,执行node knexfile.js查看输出:

console.log("加载的DB_USER:", user);
console.log("加载的DB_NAME:", database);

如果输出仍为undefined,说明.env文件路径或格式存在问题,需重新检查。

5. 指定Knex执行环境

如果迁移时使用了非默认环境(如test),需确保对应环境变量存在,或执行命令时明确指定环境:

npx knex migrate:latest --env development

内容的提问来源于stack exchange,提问作者kabirseth4

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 18:40:16