包含文件时 Node.js 上的引用错误

2023-11-26

我是新来的node.js。我有两个文件。他们是index.js and db.js

my index.js is

var connection = require('./db.js');

device = new Device({
    id: 93,
    name: 'test1'
});

device.save();

my db.js is

var mysql      = require('mysql2');
var mysqlModel = require('mysql-model');

var appModel = mysqlModel.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : 'root',
  database : 'db',
}); 

var Device = appModel.extend({
    tableName: "DeviceTable",
});

在这里我得到了error在跑步的时候节点索引.js

设备 = 新设备({

            ^

ReferenceError:设备未定义。

但是在将以下内容插入时db.js本身。效果很好。它的作用是insert.

var mysql      = require('mysql2');
var mysqlModel = require('mysql-model');

var appModel = mysqlModel.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : 'root',
  database : 'db',
}); 

var Device = appModel.extend({
    tableName: "DeviceTable",
});

var device = new Device({
    id: 93,
    name: 'test1'
});

device.save();

为什么我收到错误?


如果您希望 db 模块中的某些内容可以在其他模块中访问,则需要通过使用来公开它module.exports

添加到你的末尾db.js file:

module.exports = {
  appModel : appModel,
  Device : Device
};

然后在你的index.js你可以做:

device = new connection.Device({
  id: 93,
  name: 'test1'
});

你可以阅读更多相关内容here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

包含文件时 Node.js 上的引用错误 的相关文章

随机推荐