m2j
m2j

Reputation: 1160

Reference error on node.js while include file

I'm new to node.js. i have two files. they are 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",
});

here i'm getting the error while running node index.js

device = new Device({

            ^

ReferenceError: Device is not defined.

but while inserting the following into db.js itself. It worked fine. it does the 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 i'm getting the error?

Upvotes: 4

Views: 224

Answers (2)

Alex Morrison
Alex Morrison

Reputation: 405

node.js treats every file as a module. so to include any source file into another you need to export it at the source end and import it using require at the importing file.

Upvotes: 2

Nir Levy
Nir Levy

Reputation: 12953

if you want something from the db module to be accessible in other modules, you need to expose it, by using module.exports

add to the end of your db.js file:

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

and then in your index.js you can do:

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

you can read more about it here

Upvotes: 4

Related Questions