Original error in node.js when including file

I'm new to node.js. I have two files. they index.jsanddb.js

my index.js

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

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

device.save();

my db.js-

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",
});

here i get errorwhile running node index.js

device = new device ({

            ^

ReferenceError: device is not defined.

but when you insert the next c db.js. It worked fine. it does 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();

Why am I getting an error message?

+4
source share
2 answers

If you want something from the db module to be available in other modules, you need to set it using module.exports

add at the end of your file db.js:

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

and then in index.jsyou can do:

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

+4

node.js . , , , require .

+2

All Articles