Gulaev Valentin
Gulaev Valentin

Reputation: 595

How require works with new at node.js?

I have 'easy-db.js' module with classes inside:

const fs = require('fs');
exports.db = function () {
  this.data = {};
  this.filename = 'log/db/data.json';

  if (fs.existsSync(this.filename)) {

  }
}

Why I should use additional brackets:

const db1 = new (require('./easy-db').db)();
console.log(db1); // { data: {}, filename: 'log/db/data.json' }
const db2 = new require('./easy-db').db();
console.log(db2); // undefined  why???

Upvotes: 0

Views: 29

Answers (1)

Sebastian Speitel
Sebastian Speitel

Reputation: 7336

Because new require('./easy-db') is called before running the method .db().

Upvotes: 1

Related Questions