How does require work with new operator in node.js?

These two versions are fundamentally different.

This one:

new (require('./file')).func('r1');

Executes the require, returning the exports of ./file and then calling the new operator on the results .

This one:

var r2 = new require('./file').func('r2');

Invokes require as a constructor.


Let’s look at a more isolated and simple example:

new Date() // creates a new date object
new (Date()) // throws a TypeError: string is not a function

Leave a Comment