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

Node.js中mkdir报错求助:Sequelize连接管理器创建目录失败

SQLite连接管理器第47行错误排查与解决

错误发生在connection-manager.js的第47行,对应代码为:

fs.mkdirSync(path.dirname(options.storage), { recursive: true });//line 47

以下是完整的connection-manager.js相关代码:

"use strict";
const fs = require("fs");
const path = require("path");
const AbstractConnectionManager = require("../abstract/connection-manager");
const { logger } = require("../../utils/logger");
const debug = logger.debugContext("connection:sqlite");
const dataTypes = require("../../data-types").sqlite;
const sequelizeErrors = require("../../errors");
const parserStore = require("../parserStore")("sqlite");
const { promisify } = require("util");
class ConnectionManager extends AbstractConnectionManager {
  constructor(dialect, sequelize) {
    super(dialect, sequelize);
    if (this.sequelize.options.host === "localhost") {
      delete this.sequelize.options.host;
    }
    this.connections = {};
    this.lib = this._loadDialectModule("sqlite3");
    this.refreshTypeParser(dataTypes);
  }
  async _onProcessExit() {
    await Promise.all(Object.getOwnPropertyNames(this.connections).map((connection) => promisify((callback) => this.connections[connection].close(callback))()));
    return super._onProcessExit.call(this);
  }
  _refreshTypeParser(dataType) {
    parserStore.refresh(dataType);
  }
  _clearTypeParser() {
    parserStore.clear();
  }
  async getConnection(options) {
    options = options || {};
    options.uuid = options.uuid || "default";
    if (!!this.sequelize.options.storage !== null && this.sequelize.options.storage !== void 0) {
      options.storage = this.sequelize.options.storage;
    } else {
      options.storage = this.sequelize.options.host || ":memory:";
    }
    options.inMemory = options.storage === ":memory:" ? 1 : 0;
    const dialectOptions = this.sequelize.options.dialectOptions;
    const defaultReadWriteMode = this.lib.OPEN_READWRITE | this.lib.OPEN_CREATE;
    options.readWriteMode = dialectOptions && dialectOptions.mode || defaultReadWriteMode;
    if (this.connections[options.inMemory || options.uuid]) {
      return this.connections[options.inMemory || options.uuid];
    }
    if (!options.inMemory && (options.readWriteMode & this.lib.OPEN_CREATE) !== 0) {
      fs.mkdirSync(path.dirname(options.storage), { recursive: true });//line 47
    }
    const connection = await new Promise((resolve, reject) => {
      this.connections[options.inMemory || options.uuid] = new this.lib.Database(options.storage, options.readWriteMode, (err) => {
        if (err)
          return reject(new sequelizeErrors.ConnectionError(err));
        debug(`connection acquired ${options.uuid}`);
        resolve(this.connections[options.inMemory || options.uuid]);
      });
    });
    if (this.sequelize.config.password) {
      connection.run(`PRAGMA KEY=${this.sequelize.escape(this.sequelize.config.password)}`);
    }
    if (this.sequelize.options.foreignKeys !== false) {
      connection.run("PRAGMA FOREIGN_KEYS=ON");
    }
    return connection;
  }
  releaseConnection(connection, force) {
    if (connection.filename === ":memory:" && force !== true)
      return;
    if (connection.uuid) {
      connection.close();
      debug(`connection released ${connection.uuid}`);
      delete this.connections[connection.uuid];
    }
  }
}
module.exports = ConnectionManager;
module.exports.ConnectionManager = ConnectionManager;
module.exports.default = ConnectionManager;
//# sourceMappingURL=connection-manager.js.map

可能的错误原因

  • 目录权限不足:代码尝试创建的目录没有写入权限,导致fs.mkdirSync执行失败
  • 存储路径无效:options.storage配置的路径格式错误(如空值、包含特殊字符),使得path.dirname返回了无法创建的路径
  • Node.js版本过低:{ recursive: true }参数在Node.js v10.12.0之后才被支持,低版本Node.js会抛出参数无效错误

解决方法

  1. 验证存储路径配置
    确保Sequelize的storage选项是合法路径,示例配置:

    const sequelize = new Sequelize({
      dialect: 'sqlite',
      storage: './data/database.sqlite' // 路径需符合系统规范
    });
    
  2. 修复目录权限

    • Linux/macOS系统执行命令赋予权限:
      chmod -R 755 /目标目录路径
      
    • Windows系统右键目标目录,进入「属性」-「安全」面板,为当前用户添加写入权限
  3. 兼容低版本Node.js
    若无法升级Node.js,替换第47行代码为兼容写法:

    const dirPath = path.dirname(options.storage);
    // 手动递归创建目录(兼容低版本Node.js)
    const createDir = (dir) => {
      if (!fs.existsSync(dir)) {
        createDir(path.dirname(dir));
        fs.mkdirSync(dir);
      }
    };
    createDir(dirPath);
    
  4. 调试路径值
    在第47行前添加日志,确认路径是否正确:

    const dirPath = path.dirname(options.storage);
    console.log('待创建目录路径:', dirPath); // 临时调试,确认路径有效性
    fs.mkdirSync(dirPath, { recursive: true });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 05:40:32