无法在节点js中加载模块模型

时间:2019-09-13 06:22:42

标签: node.js express node-modules

我对节点js具有以下结构 应用

 |-node_modules  
 |-src
    -models
    -service
    -utils
    -views
    -router
    -app.js
    -index.js

内部服务中,有服务存在.js文件。 错误:找不到模块'../ models

我正在尝试加载这样的模型

我尝试查找许多示例,但没有找到根本原因。

  

var models = require(“ ../ models);

如何成功加载模型...令人惊讶的是,我能够从同一服务类加载utils。


"use strict";
module.exports = (sequelize, DataTypes) => {
  var EventsCalendar = sequelize.define("EventsCalendar", {
    eventId: { type: DataTypes.STRING(10), allowNull: false,primaryKey: true },
    eventDate : { type: DataTypes.DATE , allowNull: false },
  });

  EventsCalendar.associate = (models) => {
    EventsCalendar.belongsToMany(models.Users, {
      onDelete: "cascade",
      foreignKey: 'userId',
      as :"user"
    });
  };

  return EventsCalendar;
};

3 个答案:

答案 0 :(得分:2)

由于这个原因,您正在尝试使用语法require("../models")加载文件,但会收到错误Cannot find module '../models。 如果您在上层范围内创建了models.js文件(由于../,则一切正常。

无论如何,您都可以:

  • 加载文件:require('./myfile')
  • 在目录index.js中加载require('./my-directory/')文件
  • 将文件加载到目录中:require('./my-directory/myfile')
  • 使用相对路径require('../../my-parent-dir/myfile')
  • 将文件加载到目录中

您应该阅读官方文档作为参考,以了解how modules are loaded

答案 1 :(得分:0)

您可以在java.lang.NullPointerException: Attempt to invoke virtual method 'int com.android.server.AlarmManagerService$Batch.size()' on a null object reference at android.app.ActivityThread.handleReceiver(ActivityThread.java:3377) at android.app.ActivityThread.-wrap18(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1800) at android.os.Handler.dispatchMessage(Handler.java:110) at android.os.Looper.loop(Looper.java:232) at android.app.ActivityThread.main(ActivityThread.java:6802) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1103) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int com.android.server.AlarmManagerService$Batch.size()' on a null object reference at android.os.Parcel.readException(Parcel.java:1714) at android.os.Parcel.readException(Parcel.java:1661) at android.app.IAlarmManager$Stub$Proxy.set(IAlarmManager.java:246) at android.app.AlarmManager.setImpl(AlarmManager.java:680) at android.app.AlarmManager.setAlarmClock(AlarmManager.java:601) at com.mypackage.util.AlarmUtils.setBeforeAlert(AlarmUtils.kt:42) at com.com.mypackage.util.AzanUtils.setBeforeAlertAlarms(AzanUtils.kt:358) at com.com.mypackage.util.AzanUtils.setAlarms(AzanUtils.kt:160) 文件所在的同一文件夹中添加db.js文件。

package.json

之后,特别需要从const fs = require('fs'); const path = require('path'); const Sequelize = require('sequelize'); const basename = path.basename(module.filename); const db = {}; const config = require('./config'); const sequelize = new Sequelize({ host: config.host, database: config.databaseName, username: config.username, password: config.password, dialect: 'mysql', define: { timestamps: false }, pool: { max: 100, min: 10, idle: 200000, acquire: 1000000 } }); sequelize .authenticate() .then(() => { console.log('Connection has been established successfully.'); }) .catch(err => { console.error('Unable to connect to the database:', err); }); fs .readdirSync(__dirname + '/models') .filter(file => (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js')) .forEach(file => { const model = sequelize.import(path.join(__dirname, 'models/' + file)); db[model.name] = model; }); Object.keys(db).forEach(modelName => { if (db[modelName].associate) { db[modelName].associate(db); } }); db.sequelize = sequelize; db.Sequelize = Sequelize; module.exports = { db }; 导入所有模型,

db.js

答案 2 :(得分:0)

我发现了问题。我写成

import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper

data class Test(
    var param1: String,
    var param2: Boolean
)

fun main() {
    val mapper = jacksonObjectMapper()
    // passes, param2 is set to false, why isnt exception thrown?
    val test1 = mapper.readValue("{\"param1\": \"bah\"}", Test::class.java)
    // throws com.fasterxml.jackson.module.kotlin.MissingKotlinParameterException
    val test2 = mapper.readValue("{\"param2\": true}", Test::class.java)
}

应该是 module.export

更改后,我能够导入。