使用readdirSync和Sequelize在windows机器上读取模块时需要帮助



从同一目录读取模块时遇到以下问题。这是一个在mac和unix上运行的项目,但在windows上运行时遇到了问题。

node版本是:v16.16.0,我甚至尝试过nvm和加载不同版本的node,但所有版本的问题都是一样的。

";类型":"模块";也包含在软件包.json.中

非常感谢您的帮助!


[nodemon] restarting due to changes...
[nodemon] starting `node --experimental-specifier-resolution=node --inspect ./index.js`
Debugger listening on ws://127.0.0.1:9229/05b29298-95ff-4a2d-8445-64d74fad50b2
For help, see: https://nodejs.org/en/docs/inspector
(node:34452) ExperimentalWarning: The Node.js specifier resolution flag is experimental. It could change or be removed at any time.
(Use `node --trace-warnings ...` to show where the warning was created)
node:internal/errors:465
ErrorCaptureStackTrace(err);
^
Error [ERR_UNSUPPORTED_ESM_URL_SCHEME]: Only URLs with a scheme in: file, data are supported by the default ESM loader. On Windows, absolute paths must be valid file:// URLs. Received protocol 'd:'
at new NodeError (node:internal/errors:372:5)
at throwIfUnsupportedURLScheme (node:internal/modules/esm/resolve:1120:11)
at defaultResolve (node:internal/modules/esm/resolve:1200:3)
at ESMLoader.resolve (node:internal/modules/esm/loader:580:30)
at ESMLoader.getModuleJob (node:internal/modules/esm/loader:294:18)
at ESMLoader.import (node:internal/modules/esm/loader:380:22)
at importModuleDynamically (node:internal/modules/esm/translators:106:35)
at importModuleDynamicallyCallback (node:internal/process/esm_loader:35:14)
at loadModel (file:///D:/Storage/backend/models/index.js:32:31)
at file:///D:/Storage/backend/models/index.js:37:20 {
code: 'ERR_UNSUPPORTED_ESM_URL_SCHEME'
}
[nodemon] app crashed - waiting for file changes before starting...

文件夹结构:

后端:

- package.json
- models
- index.js
- users.js
- services.js

etc

package.json文件

"type": "module",
"description": "Project",
"main": "./index.js",
"license": "MIT",
"scripts": {
"develop": "nodemon --experimental-specifier-resolution=node --inspect ./index.js",
"start": "node --experimental-specifier-resolution=node ./index.js"
},

文件:模型>index.js


import { Sequelize, DataTypes } from 'sequelize'
import fs from 'fs'
import path from 'path'
import config from '../config.cjs'
const { DB_NAME, DB_USER, DB_PASSWORD, DB_HOST, DB_PORT } = config
const db = new Sequelize(
DB_NAME,
DB_USER,
DB_PASSWORD,
{
port: DB_PORT,
host: DB_HOST,
dialect: 'postgres',
underscored: true,
underscoredAll: true,
timestamps: false,
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
}
)
db.loadModels = async () => {
const models = await Promise.all(
fs.readdirSync(path.resolve('models'))
.reduce((acc, file) => {
if (file !== 'index.js') {
const modelPath = path.resolve('models', file)
const loadModel = async () => {
const modelFile = await import(modelPath)
const model = await modelFile.default(db, DataTypes)
return model
}
acc.push(loadModel())
}
return acc
}, []))
await Promise.all(models.map(({ associate }) => associate(db.models)))
return models
}
export default db

错误针对models/index.js:中的此行

const modelFile = await import(modelPath)

根据错误消息:,Windows上的modelPath是以d:开头的绝对文件路径

错误[ERR_UNSUPPORTED_ESM_URL_SCHEME]:默认ESM加载程序仅支持在:文件、数据中具有方案的URL。在Windows上,绝对路径必须是有效的file://URL。已接收协议"d:">

import只接受URL,因此必须使用pathToFileURL才能使其工作:

import { pathToFileURL } from 'url';
...
const modelFile = await import(pathToFileURL(modelPath))

另请参阅https://github.com/nodejs/node/issues/31710

最新更新